人物:大鸟,小菜
事件:话不多说,大鸟直接给小菜讲了中介者模式,就如联合国组织,各国之间利益不同,冲突在所难免,但是联合国是由各国的代表组成,维护国际和平和安全,它就像一个调停者,中介者的角色。
中介者模式
1.概念
2.结构图
3.代码示例
4.用处
中介者模式
1.概念:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使耦合松散,而且可以独立改变它们之间的交互
2.结构图:
3.代码展示:
Mediator类,抽象中介者类:
public abstract class Mediator { public abstract void send(String message, Colleague colleague); }
Colleague类,抽象同事类:
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator =mediator; } }
ConcreteMediator类,具体中介者类:
@Data public class ConcreteMediator extends Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; @Override public void send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.notifyColleague(message); } else { colleague1.notifyColleague(message); } } }
ConcreteColleague1类和ConcreteColleague2类,这两个是具体的同事类
@Slf4j public class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } public void send(String message) { mediator.send(message, this); } public void notifyColleague(String message) { log.info("同事1得到信息:" + message); } }
@Slf4j public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } public void send(String message) { mediator.send(message, this); } public void notifyColleague(String message) { log.info("同事2得到信息:" + message); } }
客户端调用:
public class ColleagueClient { public static void main(String[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.setColleague1(c1); m.setColleague2(c2); c1.send("吃过饭了么?"); c2.send("没有呢,你打算请客?"); } }
4.中介者的应用:一般应用于一组对象以定义良好且复杂的方式进行通信的场合,比如一个计算器页面的窗体这种定制一个分布在多个类中的行为,而又不想生成太多子类的场合