设计模式之中介者模式
来源:互联网 发布:路由器可以限制端口吗 编辑:程序博客网 时间:2024/05/16 10:58
定义
用一个中介对象来封装一系列对象之间的交互,中介者使得各个对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互.
即当程序系统中出现多对多的对象之间的相互联系时,可以考虑使用中介者模式,因为可能是系统设计的不合理造成了这种多对多的关系。
结构图
代码
//中介者接口public Interface Mediator{ public void send(String message,Colleague colleague); //定义一个发送消息的方法,得到同事对象和发送消息}
//抽象同事类public class Colleague{ protected Mediator mediator; //设置中介者对象 public Colleague(Mediator mediator) { this.mediator=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); }}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); }}
//具体中介者类public class ConcreteMediator implements Mediator{ private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public void setColleague1(ConcreteColleague1 colleague) { this.colleague1=colleague; } public void setColleague2(ConcreteColleague2 colleague) { this.colleague2=colleague; } public void send(String message,Colleague colleague) { if(colleague instanceof ConcreteColleague1) { coleague2.notify(message); } else { coleague1.notify(message); } } }
//客户端调用public static void main(Strng[] args){ ConcreteMediator mediator=new ConcreteMediator(); ConcreteColleague1 c1=new ConcreteColleague1(mediator); ConcreteColleague2 c2=new ConcreteColleague2(mediator); mediator.setColleague1(c1); mediator.setColleague2(c2); c1.send("代码写完了吗?"); c2.send("还没。。。"); }
缺点
虽然使用中介者模式减少了Colleague具体对象之间的耦合度,但也同时使得具体中介者承担了过多的责任,那么当系统中的这种多对多的相联系的对象过多时,中介者就会变得很复杂,如果它出了问题,那么整个系统也就出问题了。
0 0
- 设计模式之中介者
- 设计模式 之 中介者
- 设计模式之中介者
- 设计模式之Mediator中介者模式
- 设计模式之中介者模式
- 设计模式之中介者模式
- 八 设计模式之中介者模式
- 设计模式之--中介者模式
- 设计模式之中介者模式
- c++设计模式之中介者模式
- 设计模式之-中介者模式
- 设计模式之中介者模式
- c++设计模式之中介者模式
- 设计模式之中介者模式(Mediator)
- 设计模式之中介者模式
- 设计模式之中介者模式
- JAVA-设计模式之中介者模式
- 大话设计模式之中介者模式
- package-info.java 作用及用法详解
- AEAI Portal门户平台学习路径
- xml+xsl转换为html
- BZOJ 2527 Poi2011 Meteors 整体二分+线段树 / 可持久化线段树(MLE)
- 枚举
- 设计模式之中介者模式
- WAVE格式解码分析
- 报道,我来了啊
- 分页和分段的联系和区别
- Coordinating activities
- 内省
- Genymotion模拟器使用问题(二 Unable to connect to your virtual device!Genymotion will now)
- Android SDK Manager中Google APIs无法显示问题(附SDK Manager文件离线安装)
- 修改mysql默认字符集的方法