设计模式学习-----中介者模式
中介者模式
GOOD:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显示的相互引用,从而降低耦合;而且可以独立地改变它们之间的交互。
#include <iostream>#include <string>#include <vector>using namespace std;class Colleague;//中介者类class Mediator{public:virtual void Send(string message,Colleague* col) = 0;};//抽象同事类class Colleague{protected:Mediator* mediator;public:Colleague(Mediator* temp){mediator = temp;}};//同事一class Colleague1 : public Colleague{public:Colleague1(Mediator* media) : Colleague(media){}void Send(string strMessage){mediator->Send(strMessage,this);}void Notify(string strMessage){cout<<"同事一获得了消息"<<strMessage<<endl;}};//同事二class Colleague2 : public Colleague{public:Colleague2(Mediator* media) : Colleague(media){}void Send(string strMessage){mediator->Send(strMessage,this);}void Notify(string strMessage){cout<<"同事二获得了消息"<<strMessage<<endl;}};//具体中介者类class ConcreteMediator : public Mediator{public:Colleague1 * col1;Colleague2 * col2;virtual void Send(string message,Colleague* col){if(col == col1)col2->Notify(message);else col1->Notify(message);}};//客户端:int main(){ConcreteMediator * m = new ConcreteMediator();//让同事认识中介Colleague1* col1 = new Colleague1(m);Colleague2* col2 = new Colleague2(m);//让中介认识具体的同事类m->col1 = col1;m->col2 = col2;col1->Send("吃饭了吗?");col2->Send("还没吃,你请吗?");return 0;}//转载请注明,文章来自:http://blog.csdn.net/windows_nt