大话设计模式中介者模式模式c++实现

本文详细探讨了设计模式中的中介者模式,并重点介绍了如何在C++中实现这一模式,通过实例解析其核心思想与其他23种设计模式的关系。
摘要由CSDN通过智能技术生成

中介者模式

其他二十三种设计模式

#include<iostream>
using namespace std;

//中介者模式
class Country;

//联合国机构
class UnitedNations {
public:
	virtual void Declare(string _message, Country* _colleague) = 0;
};

//国家
class Country {
public:
	Country(UnitedNations* _mediator) {
		this->mediator = _mediator;
	}

protected:
	UnitedNations* mediator;
};

//具体国家类
class USA :public Country {
public:
	USA(UnitedNations* _mediator) :Country(_mediator) {}

	void Declare(string _message) {
		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) {
		mediator->Declare(_message, this);
	}
	void GetMessage(string _message) {
		cout << "伊拉克获得的信息:" << _message << endl;
	}
};

//联合国安理会
class UnitedNationsSecurityCouncil :public UnitedNations {
public:
	USA* Colleague1(Country* _country) {
		this->colleague1 = (USA*)_country;
		return this->colleague1;
	}
	Iraq* Colleague2(Country* _country) {
		this->colleague2 = (Iraq*)_country;
		return this->colleague2;
	}

	virtual void Declare(string _message, Country* _colleague) {
		if (_colleague == colleague1)
			colleague2->GetMessage(_message);
		else
			colleague1->GetMessage(_message);
	}

private:
	USA* colleague1 = NULL;
	Iraq* colleague2 = NULL;
};

void test1() {
	UnitedNationsSecurityCouncil* UNSC = new UnitedNationsSecurityCouncil;
	USA* c1 = new USA(UNSC);
	Iraq* c2 = new Iraq(UNSC);

	UNSC->Colleague1(c1);
	UNSC->Colleague2(c2);

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

	delete c2;
	delete c1;
	delete UNSC;
}

int main() {
	test1();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值