中介者模式详解

中介者模式

简介通过引入一个中介者对象来封装和协调多个对象之间的交互,从而降低对象间的耦合度。
人话:就是两个类或者系统之间, 不要直接互相调用, 而是要中间的类来专门进行交互。
举个例子
比如两个国家之间(关系差, 没有大使馆), 需要联合国作为中介进行对话.

class Country;


class UnitedNations
{
public:
	vector<Country*> _countries;
	void add_contry(Country* c);
	void send(string s);
};


class Country
{
private:
	UnitedNations* un;
public:
	Country(UnitedNations* u) : un(u) {};
	UnitedNations* get_un() { return un; };
	virtual void speek(string s) = 0;
	virtual void listen(string s) = 0;
};


void UnitedNations::add_contry(Country* c)
{
	_countries.push_back(c);
}


void UnitedNations::send(string s)
{
	for (Country* c : _countries)
		c->listen(s);
}


class China : public Country
{
public:
	China(UnitedNations* un) : Country(un) {};
	void speek(string s) override
	{
		cout << "China said : " << s << endl;
		get_un()->send(s);
	}
	void listen(string s)override
	{
		cout << "----China get : " << s << endl;
	}
};


class America : public Country
{
public:
	America(UnitedNations* un) : Country(un) {};
	void speek(string s) override
	{
		cout << "America said : " << s << endl;
		get_un()->send(s);
	}
	void listen(string s)override
	{
		cout << "----America get : " << s << endl;
	}
};


class Russia : public Country
{
public:
	Russia(UnitedNations* un) : Country(un) {};
	void speek(string s) override
	{
		cout << "Russia said : " << s << endl;
		get_un()->send(s);
	}
	void listen(string s)override
	{
		cout << "----Russia get : " << s << endl;
	}
};



int main()
{
	UnitedNations* un = new UnitedNations();
	China* c = new China(un);
	America* a = new America(un);
	Russia* r = new Russia(un);

	un->add_contry(c);
	un->add_contry(a);
	un->add_contry(r);

	r->speek("美国, 你爹来了");
	a->speek("呵呵, 笑死");
	c->speek("大家文明讲话");

	return 0;
}

执行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值