基本介绍:

    1. 中介者模式(Mediator Pattern),用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互
    2. 中介者模式属于行为型模式,使代码易于维护
    3. 比如MVC模式,C(Controller控制器)是M(Model模型)和V(View视图)的中介者,在前后端交互时起到了中间人的作用

    中介者模式类图:
    image.png

    中介者角色说明:

    1. Mediator:抽象中介者,定义了同事对象到中介者对象的接口
    2. Colleague:抽象同事类
    3. ConcreteMediator:具体的中介者对象,实现抽象方法,它徐需要知道所有的具体的同事类,即以一个集合来管理HashMap,并接受某个同事对象消息,完成相应的任务
    4. ConcreteColleague:具体的同事类,会有很多,每个同事只知道自己的行为,而不了解其他同事类的行为(方法),但是它们都依赖中介者对象

    代码示例:

    1. public abstract class Mediator {
    2. /**
    3. * 发送消息
    4. * @param message 消息
    5. * @param colleague 发送同事
    6. */
    7. public abstract void send(String message, Colleague colleague);
    8. }
    9. public abstract class Colleague {
    10. /**
    11. * 通知信息
    12. * @param message 消息
    13. */
    14. public abstract void notifyMessage(String message);
    15. }
    16. public class ConcreteMediator extends Mediator {
    17. @Override
    18. public void send(String message, Colleague colleague) {
    19. colleague.notifyMessage(message);
    20. }
    21. }
    22. public class ConcreteColleagueA extends Colleague {
    23. @Override
    24. public void notifyMessage(String message) {
    25. System.out.println("A收到消息:"+message);
    26. }
    27. }
    28. public class ConcreteColleagueB extends Colleague {
    29. @Override
    30. public void notifyMessage(String message) {
    31. System.out.println("B收到消息:"+message);
    32. }
    33. }
    34. public class Client {
    35. public static void main(String[] args) {
    36. ConcreteMediator mediator = new ConcreteMediator();
    37. mediator.send("message", new ConcreteColleagueA());
    38. mediator.send("message", new ConcreteColleagueB());
    39. }
    40. }

    示例结果:

    1. A收到消息:message
    2. B收到消息:message

    中介者模式的注意事项和细节:

    1. 多个类相互耦合,会形成网状结构,使用中介者模式将网状结构分离为星型结构,进行解耦
    2. 减少类间依赖,降低了耦合,符合迪米特原则
    3. 中介者承担了较多的责任,一旦中介者出现了问题,整个系统就会受到影响
    4. 如果设计不当,中介者对象本身变得过于复杂,这点在实际使用时,要特别注意