Mediator模式(C++中介者模式含个人Demo源码)
来源:互联网 发布:清华软件学院位置 编辑:程序博客网 时间:2024/04/27 16:18
重新温习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;}
1 0
- Mediator模式(C++中介者模式含个人Demo源码)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- Mediator(中介者模式)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- Mediator(中介者)模式
- 中介者模式(Mediator)
- 中介者(Mediator)模式
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 中介者模式(Mediator)
- 汪汪汪
- 如何清除SQL Server Management Studio的最近服务器列表
- 二叉排序树
- 6174问题
- FFmpeg+SDL视频播放(4)
- Mediator模式(C++中介者模式含个人Demo源码)
- HTML+CSS入门笔记二之HTML+CSS核心内容
- SDUT OJ 数据结构实验之队列一:排队买饭
- 学习笔记2---html的一些标签
- UI界面效果研究2
- Ubuntu防火墙设置及开启SSHD服务,同时使用putty远程连接到ubuntu
- java开发环境jdk的安装及使用
- 前置及后置++_--
- Cow code