#pragma once
#include "stdafx.h"
#include<map>
#include<set>
#include<string>
#include<iostream>
using namespace std;

/*
	设计模式-中介者模式(Mediator)
	用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要
显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
中介者模式的有点来自集中控制,其缺点也是他,中介者模式一般应用于一组对象
定义良好但是复杂的方式进行通讯的场合,以及想定制一个分布式在多个类中的行为,
而又不想生成太多的子类的场合。
*/

class CMediator {//抽象中介者
public:
	virtual void Send(const string &strPeople, const string &strMessage) = 0;
};

class CColleague {//抽象同事类
protected:
	CMediator *mpMediator;
public:
	CColleague(CMediator *pMediator) {
		mpMediator = pMediator;
	}
	virtual void Notify(const string &strMessage) = 0;
};

class CConcreteColleague1 :public CColleague {//同事类1
public:
	CConcreteColleague1(CMediator *pMediator) :CColleague(pMediator) {}
	void Send(const string &strPeople, const string &strMessage) {
		mpMediator->Send(strPeople , strMessage);
	}
	void Notify(const string &strMessage) {
		cout << "tong shi 1 de dao xin xi:" << strMessage << endl;
	}
};

class CConcreteColleague2 :public CColleague {//同事类2
public:
	CConcreteColleague2(CMediator *pMediator) :CColleague(pMediator) {}
	void Send(const string &strPeople, const string &strMessage) {
		mpMediator->Send(strPeople, strMessage);
	}
	void Notify(const string &strMessage) {
		cout << "tong shi 2 de dao xin xi:" << strMessage << endl;
	}
};

class CConcreteMediator :public CMediator {//具体中介者类
private:
	map<string, CColleague*>mpColleague;
public:
	CConcreteMediator() {mpColleague.clear();}
	void Send(const string &strPeople, const string &strMessage) {
		mpColleague[strPeople]->Notify(strMessage);
	}
	void AddColleague(const string &strPeople ,CColleague * pColleague) {
		mpColleague[strPeople] = pColleague;
	}
};


int main() {

	CConcreteMediator *pM = new CConcreteMediator();
	CConcreteColleague1 *pC1 = new CConcreteColleague1(pM);
	CConcreteColleague2 *pC2 = new CConcreteColleague2(pM);
	pM->AddColleague("pC1", pC1);
	pM->AddColleague("pC2", pC2);

	pC1->Send("pC2","chi fan mei?");
	pC2->Send("pC1", "mei ne");

	delete pM, delete pC1, delete pC2;

	getchar();
	return 0;
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐