设计模式之中介者模式
1、定义
中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使耦合松散,而且可以独立的改变他们之间的交互。
|
2、UML
各个类说明:
|
3、优点:
|
4、缺点:
由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteMediator都复杂
|
5、适合应用场景:
中介者模式一般应用于一组对象以定义良好,但是复杂的方式进行通信的场合,比如窗体Form对象或Web页面aspx,以及想定制一个分部在多个类中的行为,而又不想生成太多的子类的场合。
|
6、例子:
写个例子练练手
package com.zcr.Mediator; //抽象同事类 public abstract class Colleague { protected Mediator mediator; //构造方法,得到中介者对象 public Colleague(Mediator mediator) { this.mediator = mediator; } }
package com.zcr.Mediator; 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); } }
package com.zcr.Mediator; public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); // TODO Auto-generated constructor stub } public void Send(String message) { mediator.Send(message, this); } public void Notify(String message) { System.out.println("同事2得到消息:"+message); } }
package com.zcr.Mediator; public class ConcreteMediator extends Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 getColleague1() { return colleague1; } public void setColleague1(ConcreteColleague1 colleague1) { this.colleague1 = colleague1; } public ConcreteColleague2 getColleague2() { return colleague2; } public void setColleague2(ConcreteColleague2 colleague2) { this.colleague2 = colleague2; } @Override public void Send(String message, Colleague colleague) { if(colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } }
package com.zcr.Mediator; //抽象中介者类 public abstract class Mediator { //定义一个抽象的发送消息的方法,得到同时对象和发送消息 public abstract void Send(String message,Colleague colleague); }
package com.zcr.Mediator; public class MediatorTest { 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("没有呢,打算请客?"); } }
运行结果:
因为是初学者,例子比较简单,忘见谅。