码迷,mamicode.com
首页 > 其他好文 > 详细

Mediator中介者模式(含个人Demo源码)

时间:2014-12-05 09:21:35      阅读:220      评论:0      收藏:0      [点我收藏+]

标签: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;

}


 

 

Mediator中介者模式(含个人Demo源码)

标签:style   io   color   os   sp   for   on   bs   ad   

原文地址:http://blog.csdn.net/yc7369/article/details/41733519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!