中间者模者模式原理:中介者维持所有要交互对象的指针或者对象,所有对象维持一个中介者的指针或者对象。
#include <iostream> #include <string> using namespace std; class Mediator; class Person { public: virtual GetMessage(string message) { } virtual void SendMessage(string message) { } virtual void SetMediator(Mediator *pmdiator) { } protected: Mediator *m_pmediator; }; class Mediator { public: void Send(string message,Person *person) { if (person == m_renter) { m_landlord->GetMessage(message); } else { m_renter->GetMessage(message); } } void SetRenter(Person *prenter) { m_renter = prenter; } void SetLandlord(Person *plandlord) { m_landlord = plandlord; } private: Person *m_renter; Person *m_landlord; }; class Renter:public Person { public: virtual GetMessage(string message) { cout << "租客收到租房信息:"<<message<<endl; } virtual void SendMessage(string message) { m_pmediator->Send(message,this); } virtual void SetMediator(Mediator *pmediator) { m_pmediator = pmediator; } }; class Landlord:public Person { public: virtual GetMessage(string message) { cout << "房东收到租房信息:"<<message<<endl; } virtual void SendMessage(string message) { m_pmediator->Send(message,this); } virtual void SetMediator(Mediator *pmediator) { m_pmediator = pmediator; } }; int main() { Mediator *pmediator = new Mediator(); Person *prenter = new Renter(); Person *plandlord = new Landlord(); pmediator->SetLandlord(plandlord); pmediator->SetRenter(prenter); prenter->SetMediator(pmediator); plandlord->SetMediator(pmediator); prenter->SendMessage("我要租一个有网的房子"); plandlord->SendMessage("我现在有一个两室一厅的房子要出租"); return 0; }