标签:
GOF:用一个中介对象来封装一系列的对象交互。中介者使对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
类图:
适用性:
优缺:
模板代码:
#include <iostream> #include <string> using namespace std; class Colleague; class Mediator { public: virtual void send(string message, Colleague *pColleague) = 0; }; class Colleague { public: Colleague(Mediator *pMediator) { m_pMediator = pMediator; } void notify(string message) { cout << "Got message : " << message << endl; } protected: Mediator *m_pMediator; }; class ConcreteColleague1 : public Colleague { public: ConcreteColleague1(Mediator *pMediator) : Colleague(pMediator) {} void send(string message) { m_pMediator->send(message, this); } void notify(string message) { cout << "Colleague1 got message : " << message << endl; } }; class ConcreteColleague2 : public Colleague { public: ConcreteColleague2(Mediator *pMediator) : Colleague(pMediator) {} void send(string message) { m_pMediator->send(message, this); } void notify(string message) { cout << "Colleague2 got message : " << message << endl; } }; class ConcreteMediator : public Mediator { public: void setColleague1(ConcreteColleague1 *pColleague1) { m_pColleague1 = pColleague1; } void setColleague2(ConcreteColleague2 *pColleague2) { m_pColleague2 = pColleague2; } void send(string message, Colleague *pColleague) { if(pColleague == m_pColleague1) { m_pColleague2->notify(message); } else { m_pColleague1->notify(message); } } private: ConcreteColleague1 *m_pColleague1; ConcreteColleague2 *m_pColleague2; }; int main() { ConcreteMediator *pcm = new ConcreteMediator();; ConcreteColleague1 *pc1 = new ConcreteColleague1(pcm); ConcreteColleague2 *pc2 = new ConcreteColleague2(pcm); pcm->setColleague1(pc1); pcm->setColleague2(pc2); pc1->send("message from pc1"); return 0; }
中介者模式就是封装了多个类之间的交互,使得我们不需要直接在多个类之间手动弄交互。
如下所示:
------------>
但是这样就使得中介者变得复杂了,需要小心管理。
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/4524815.html