c++ 设计模式--中介者模式(22)

案例:American和Iraq通过联合国会话

中介者模式

中介者模式简介(MediatorPattern)

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

中介者模式结构

  • Mediator(抽象中介者): 声明用于一系列对象之间交互的接口
  • ConcreteMediator(具体中介者): 聚合了一系列交互对象,实现交互
  • Colleague(抽象交互对象): 声明交互的公共接口,维护了一个抽象中介者引用
  • ConcreteColleague(具体交互对象): 实现交互的接口,由具体中介者完成交互

在这里插入图片描述

中介者模式示例

https://gitee.com/NiMiKiss/design-pattern.git

#ifndef _MEDIATOR_PATTERN_
#define _MEDIATOR_PATTERN_
#include<iostream>
enum CountryName
{
	USA = 1,
	IRAQ
};

class Country;
class UnitedNations
{
public:
	virtual void Declare(const std::string& sMessage, Country* spColleague) = 0;
};

class Country
{
public:
	Country(std::shared_ptr<UnitedNations> spUnitedNations, CountryName eCountryName) :
		m_spUnitedNations(spUnitedNations), m_eCountryName(eCountryName) {}
	virtual void Declare(const std::string& sMessage) { m_spUnitedNations->Declare(sMessage, this); }
	CountryName GetCountryName() { return m_eCountryName; }
protected:
	std::shared_ptr<UnitedNations> m_spUnitedNations;
	CountryName m_eCountryName;
};

class American :public Country
{
public:
	American(std::shared_ptr<UnitedNations> spUnitedNations) :Country(spUnitedNations, USA) {}
	void GetMessage(const std::string& sMessage)
	{
		std::cout << "美国获得对方的信息" << sMessage << std::endl;
	}
};

class Iraq :public Country
{
public:
	Iraq(std::shared_ptr<UnitedNations> spUnitedNations) :Country(spUnitedNations, IRAQ) {}
	void GetMessage(const std::string& sMessage)
	{
		std::cout << "伊拉克获得对方的信息" << sMessage << std::endl;
	}
};

class UnitedNationsSecurityConcil :public UnitedNations
{
public:
	void SetAmericanContry(std::shared_ptr<American> spUSA) { m_spUSA = spUSA; }
	void SetIraqContry(std::shared_ptr<Iraq> spIraq) { m_spIraq = spIraq; }
	void Declare(const std::string& sMessage, Country* spColleague)
	{
		switch (spColleague->GetCountryName())
		{
		case USA:
			m_spIraq->GetMessage(sMessage);
			break;
		case IRAQ:
			m_spUSA->GetMessage(sMessage);
			break;
		default:
			break;
		}
	}
private:
	std::shared_ptr<American> m_spUSA;
	std::shared_ptr<Iraq> m_spIraq;
};
#endif // !_MEDIATOR_PATTERN_

客户端调用

#include "Mediator_Pattern.h"
#include<iostream>

int main()
{
	auto spUnitedNationsSecurityConcil = std::shared_ptr<UnitedNationsSecurityConcil>(new UnitedNationsSecurityConcil());
	auto spAmerican = std::shared_ptr<American>(new American(spUnitedNationsSecurityConcil));
	auto spIraq = std::shared_ptr<Iraq>(new Iraq(spUnitedNationsSecurityConcil));

	spAmerican->Declare("不准研制核武器,否则要发动战争");
	spIraq->Declare("我们没有核武器,也不怕侵略");
	return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值