设计模式:中介者模式
来源:互联网 发布:mac怎么连接vps 编辑:程序博客网 时间:2024/05/16 06:30
中介者模式(Mediator):
用一个中介对象来封装一系列的对象交互,使各对象不必显式的相互引用,松耦合,而且可以独立改变它们之间的交互。
迪米特法则:
如果两个类不必彼此直接通信,那么这两个类就不应该发生直接的相互作用,如果其中一个类要调用另一个类的方法时,可以用中介者转发这个调用。
例如,A国和B国通过联合国通信,联合国为中介者。
#include<iostream>#include<string>using namespace std;class Country;class UnitedNations {public:virtual void setA(Country* a)=0;virtual void setB(Country* b)=0;virtual ~UnitedNations() {}virtual void send(string message,Country* sender)=0;};class Country {protected:UnitedNations* pUnitedNations;public:Country(UnitedNations* UN):pUnitedNations(UN) {}virtual ~Country() {}virtual void send(string message)=0;virtual void get(string message)=0;};class ConcreteCountryA:public Country {public:ConcreteCountryA(UnitedNations* UN):Country(UN) {}void send(string message) {pUnitedNations->send(message,this);}void get(string message) {cout<<"A国收到:"+message<<endl;}};class ConcreteCountryB:public Country {public:ConcreteCountryB(UnitedNations* UN):Country(UN) {}void send(string message) {pUnitedNations->send(message,this);}void get(string message) {cout<<"B国收到:"+message<<endl;}};class UnitedSecurity:public UnitedNations {private:Country* A;Country* B;public:void setA(Country* a){A=a;} void setB(Country* b){B=b;} void send(string message,Country* sender) {if(sender==A) {cout<<"A国宣称:"+message<<endl;B->get(message);}if(sender==B) {cout<<"B国宣称:"+message<<endl;A->get(message);}}};int main() {UnitedNations* betweenAB=new UnitedSecurity();Country* CountryA=new ConcreteCountryA(betweenAB);Country* CountryB=new ConcreteCountryB(betweenAB);betweenAB->setA(CountryA);betweenAB->setB(CountryB);CountryA->send("不准生产核武器!");CountryB->send("从未生产核武器!"); delete betweenAB;delete CountryA;delete CountryB;return 0;}
中介者UnitedNations的存在使得ConcreteCountryA与ConcreteCountryB之间耦合度减小,使得它们可以独立的改变和复用,将交互复杂性转变为中介者复杂性。
0 0
- 【设计模式】中介者
- 中介者设计模式
- 设计模式-中介者
- 设计模式-中介者
- [设计]中介者模式
- 设计模式 中介者模式
- 设计模式-中介者模式
- 设计模式 - 中介者模式
- 设计模式-中介者模式
- 设计模式:中介者模式
- 设计模式--中介者模式
- 设计模式-中介者模式
- 设计模式--中介者模式
- 设计模式-中介者模式
- 设计模式-中介者模式
- 设计模式-中介者模式
- 【设计模式】中介者模式
- 设计模式:中介者模式
- Android corners 与 solid
- Android中Touch事件的处理逻辑
- TOEFL一战(2016年1月24日)
- SOLR使用手册之操作collection
- 最近写的几段小工具代码
- 设计模式:中介者模式
- 两个链表的第一个公共结点
- 关于spring切面的一点理解,记录一下
- 机顶盒业务相关
- 高德导航断网后恢复网络不重新规划路径问题及解决方案
- java起线程超级简单例子(咋个办呢 zgbn)
- 开涛的springMVC教程读书笔记
- GSS系列(1)——GSS1&&GSS3
- VNC远程桌面到linux,提示connection refused(10061)解决办法