-
中介者模式(Mediator),用一个中介对象来封装一系列对象交互。中介者使各对象不需要显示地相互引用,从而使耦合松散,而且可以独立地改变他们之间的交互。
-
由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
-
中介者模式的优点来自集中控制,其缺点也是他。
-
Mediator.java
/** * 抽象中介类 */ public abstract class Mediator { public abstract void send(String message,Colleague colleague); }
-
ConcreteMediator .java
/** * 中介实例类 */ public class ConcreteMediator extends Mediator{ private ConcreteColleague1 concreteColleague1; private ConcreteColleague2 concreteColleague2; public void setConcreteColleague1(ConcreteColleague1 concreteColleague1) { this.concreteColleague1 = concreteColleague1; } public void setConcreteColleague2(ConcreteColleague2 concreteColleague2) { this.concreteColleague2 = concreteColleague2; } @Override public void send(String message, Colleague colleague) { if (colleague == concreteColleague1) { concreteColleague2.notify(message); }else { concreteColleague1.notify(message); } } }
-
Colleague.java
/** * 同事抽象类 */ public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } }
-
ConcreteColleague1.java
public class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } public void send(String message) { mediator.send(message, this); } public void notify(String message) { System.out.println("同事1得到消息:" + message); } }
-
ConcreteColleague2.java
public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } public void send(String message) { mediator.send(message, this); } public void notify(String message) { System.out.println("同事2得到消息:" + message); } }
-
Main.java
public class Main { public static void main(String[] args) { final ConcreteMediator m = new ConcreteMediator(); final ConcreteColleague1 c1 = new ConcreteColleague1(m); final ConcreteColleague2 c2 = new ConcreteColleague2(m); m.setConcreteColleague1(c1); m.setConcreteColleague2(c2); c1.send("吃过饭了么"); c2.send("没有呢"); } }
23种设计模式之中介者模式(18)
最新推荐文章于 2024-03-29 23:31:44 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)