标签:style io color os sp for on bs ad
重新温习GOF23到第18个中介者模式了,感觉还是蛮不错的,写了一个小小的Demo来解释下他们之间的关系。
中介者模式其实就相当于:中介,租房人,还有房主三者之间的关系。
房主A,租房人B首先联系了中介,在中介那里记名字了。
房主A有空房了,发条消息给中介,中介将A有空房的消息发给其他人。
在此之上,demo做了小小扩充,当又有租房人C联系中介,B发了条消息,A与C都会收到B的消息。
#include <iostream> #include <vector> using namespace std; #include <crtdbg.h> class Person; class Mediator { public: virtual void SendMsg(string msg, Person *pItem) = 0; }; class Person { public: Person(Mediator *pMediator):m_pMediator(pMediator) { } virtual void Say(string msg) = 0; virtual void GetMsg(string msg) = 0; protected: Mediator *m_pMediator; }; class PersonA : public Person { public: PersonA(Mediator *pMediator):Person(pMediator) { } virtual void Say(string msg) { cout<<"PersonA said:"<<endl; m_pMediator->SendMsg(msg, this); } void GetMsg(string msg) { cout<<"PersonA GetMsg: "<<msg.c_str()<<endl; } }; class PersonB : public Person { public: PersonB(Mediator *pMediator):Person(pMediator) { } virtual void Say(string msg) { cout<<"PersonB said:"<<endl; m_pMediator->SendMsg(msg, this); } void GetMsg(string msg) { cout<<"PersonB GetMsg: "<<msg.c_str()<<endl; } private: }; class PersonC : public Person { public: PersonC(Mediator *pMediator):Person(pMediator) { } virtual void Say(string msg) { cout<<"PersonC said:"<<endl; m_pMediator->SendMsg(msg, this); } void GetMsg(string msg) { cout<<"PersonC GetMsg: "<<msg.c_str()<<endl; } private: }; class ConcreateMediator : public Mediator { private: vector<Person*> conentList; public: void AddFriend(Person* pPerson) // 没有添加该好友,则添加进去 { vector<Person*>::iterator iter = conentList.begin(); for (; iter != conentList.end(); iter++) { if(*iter == pPerson) break; } if(iter == conentList.end()) { conentList.push_back(pPerson); } } void SendMsg(string msg, Person *pItem) //如假设A不认识其他人,A发送信息,通过中介,则可以发送给其他的人 { vector<Person*>::iterator iter = conentList.begin(); while(iter != conentList.end()) { if(*iter != pItem) (*iter)->GetMsg(msg); iter++; } } }; void main() { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF) | _CRTDBG_LEAK_CHECK_DF); ConcreateMediator *pMediator = new ConcreateMediator(); Person *pA = new PersonA(pMediator); Person *pB = new PersonB(pMediator); Person *pC = new PersonC(pMediator); pMediator->AddFriend(pA); pMediator->AddFriend(pB); pA->Say("call JesonYang"); pMediator->AddFriend(pC); pB->Say("demo by yc7369"); delete pA; delete pB; delete pC; delete pMediator; }
标签:style io color os sp for on bs ad
原文地址:http://blog.csdn.net/yc7369/article/details/41733519