c++ 中介者模式(mediator)
中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。中介者模式的例子很多,大到联合国安理会,小到房屋中介。下面以房屋中介来介绍中介者模式。
#include <iostream> #include <string> using namespace std; class Mediator; class Person { public: virtual void setMediator(Mediator* mediator){}; virtual void sendMessage(string msg) = 0; virtual void getMessage(){}; protected: Mediator *m_mediator; }; class Mediator { public: virtual void setHost(Person* p) = 0; virtual void setClient(Person* p) = 0; virtual void sendMsg(Person* p,string msg) { } }; class HouseMediator:public Mediator { public: void setHost(Person* p) { m_host = p; } void setClient(Person* p) { m_client = p; } void sendMsg(Person* p,string msg) { if(p == m_host) { m_client->getMessage(); } else { m_host->getMessage(); } } private: Person* m_host; Person* m_client; }; class HostPerson:public Person { public: void setMediator(Mediator* mediator) { m_mediator = mediator; } void sendMessage(string msg) { m_mediator->sendMsg(this,msg); } void getMessage(string msg) { cout << "房东收到消息!" <<endl; } }; class ClientPerson:public Person { public: void setMediator(Mediator* mediator) { m_mediator = mediator; } void sendMessage(string msg) { m_mediator->sendMsg(this,msg); } void getMessage(string msg) { cout << "客户收到消息!" <<endl; } };
接口使用
#include "mediator.h" int main() { HouseMediator *mediator = new HouseMediator(); HostPerson *host = new HostPerson(); host->setMediator(mediator); ClientPerson *client = new ClientPerson(); client->setMediator(mediator); mediator->setClient(client); mediator->setHost(host); client->sendMessage("我要租房子!"); host->sendMessage("有房子要出租!"); return 0; }
博客参照:
http://blog.csdn.net/wuzhekai1985/article/details/6673603