设计模式-中介者模式

中介者模式Mediator):

    用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。


中介者模式的优缺点
    1.中介者模式很容易在系统中使用,也很容易在系统中误用。当系统出现了‘多对多’交互复杂的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是不是合理。
    2.中介者模式的优点是首先Mediator的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator,比如任何国家的改变不会影响到其他国家,而只是与安理会发生变化。
    3.其次,由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转义到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
    4.缺点也比较明显,由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
    5.中介者模式的优点来自集中控制,其缺点也是它。
    6.中介者模式一般应用于一组对象定义良好但是复杂的方式进行通信的场合,以及想定制一个分布式在多个类中的行为,而又不想生成太多的子类的场合。

中介者模式实现代码:

#pragma once

#include <map>
#include <string>
#include <iostream>
using namespace std;

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

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

//ConcreteColleague1和ConcreteColleague2等各种同事类

class CConcreteColleague1 : public CColleague
{
public:
	CConcreteColleague1(CMediator *pMediator):CColleague(pMediator)
	{

	}
	void Send(const string &strPeople ,const string &strMessage)
	{
		m_pMediator->Send(strPeople ,strMessage);
	}
	void Notify(const string &strMessage)
	{
		cout<<"tong shi 1 de dao xin xi:"<<strMessage<<endl;
	}
};

class CConcreteColleague2 : public CColleague
{
public:
	CConcreteColleague2(CMediator *pMediator):CColleague(pMediator)
	{

	}
	void Send(const string &strPeople ,const string &strMessage)
	{
		m_pMediator->Send(strPeople ,strMessage);
	}
	void Notify(const string &strMessage)
	{
		cout<<"tong shi 2 de dao xin xi:"<<strMessage<<endl;
	}
};

//ConcreteMediator类 具体中介者类
class CConcreteMediator : public CMediator
{
private:
	map<string ,CColleague *> m_pColleague;
public:
	CConcreteMediator()
	{
		m_pColleague.clear();
	}
	void Send(const string &strPeople ,const string &strMessage)
	{
		//实际过程中此处记得容错处理
		m_pColleague[strPeople]->Notify(strMessage);
	}
	void AddColleague(const string &strPeople ,CColleague * pColleague)
	{
        m_pColleague[strPeople] = pColleague;
	}
};
客户端调用:

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include "MediatorMode.h"

using namespace std;

int main()
{
    CConcreteMediator *p_M = new CConcreteMediator();
	CConcreteColleague1 *p_C1 = new CConcreteColleague1(p_M);
	CConcreteColleague2 *p_C2 = new CConcreteColleague2(p_M);
	p_M->AddColleague("p_C1" ,p_C1);
	p_M->AddColleague("p_C2" ,p_C2);

	p_C1->Send("p_C2" ,"chi fan mei?");
	p_C2->Send("p_C1" ,"bing mei you, ni yao qing ke?");

	delete p_M;
	delete p_C1;
	delete p_C2;
	return 0;
}
执行结果:



原文地址:https://www.cnblogs.com/csnd/p/12062322.html