设计模式:中介者模式

来源:互联网 发布: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
原创粉丝点击