第25章中介者模式

一 概念

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

二 UML图

  • Mediator 抽象中介者,定义了同事对象到中介者对象的接口
  • Colleague 抽象同事类
  • ConcreteMediator 具体中介者对象,实现抽象类方法,它需要知道所有具体同事类,并从具体同事接收消息,向具体同事对象发出命令。
  • ConcreteColleague1 具体同事类,每个具体同事只知道自己的行为,而不了解其它同事类的情况,但他们却都认识中介者对象

三 C++代码实现

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;

class UnitedNations;

//抽象的国家类 相当于Colleague
class Country
{
public:
	Country(UnitedNations* mediator)
	{
		this->m_mediator = mediator;
	}
protected:
	UnitedNations* m_mediator;
};

//联合国类 相当于Mediator类
class UnitedNations
{
public:
	//定义一个抽象的发送消息方法,得到同事对象和发送信息
	virtual void Declare(string message, Country* colleague) = 0;
};

//美国类 相当于ConcreteColleague1类
class USA : public Country
{
public:
	USA(UnitedNations* mediator) : Country(mediator)
	{

	}
	//声明  发送信息通常是中介者发送出去的
	void Declare(string message)
	{
		this->m_mediator->Declare(message, this);
		
	}
	void GetMessage(string message)
	{
		cout << "美国获得对方信息: " << message << endl;
	}
};

//伊拉克类 
class Iraq : public Country
{
public:
	Iraq(UnitedNations* mediator) : Country(mediator)
	{

	}
	//声明  发送信息通常是中介者发送出去的
	void Declare(string message)
	{
		this->m_mediator->Declare(message, this);
	}
	void GetMessage(string message)
	{
		cout << "伊拉克获得对方信息: " << message << endl;
	}
};

//联合国安全理事会 
//ConcreteMediator 具体中介者对象,实现抽象类的方法,它需要知道
//所有具体同事类,并从具体同事接收消息,向具体同事对象发出命令
class UnitedNationsSecurityCouncil : public UnitedNations
{
public:
	void SetUSAColleague(USA* colleague1)
	{
		this->m_colleague1 = colleague1;
	}
	void SetIraqColleague(Iraq* colleague2)
	{
		this->m_colleague2 = colleague2;
	}
	void Declare(string message, Country* colleague) override
	{
		if (colleague == this->m_colleague1)
		{
			cout << colleague << ' '<< this->m_colleague1 << endl;
			this->m_colleague2->GetMessage(message);
		}
		else
		{
			this->m_colleague1->GetMessage(message);
		}
	}
private:
	USA* m_colleague1;  //它需要知道所有具体同事类
	Iraq* m_colleague2;
};

int main()
{
	UnitedNationsSecurityCouncil* UNSC = new UnitedNationsSecurityCouncil();
	USA* c1 = new USA(UNSC);
	Iraq* c2 = new Iraq(UNSC);

	UNSC->SetUSAColleague(c1);
	UNSC->SetIraqColleague(c2);

	c1->Declare("不准研制核武器,否则要发动战争");
	c2->Declare("我们没有核武器,也不怕侵略战争!");

	return 0;
}

原文地址:https://www.cnblogs.com/Manual-Linux/p/11156270.html