设计模式C++版:第十三式中介者模式

中介者模式通过集中控制多个对象之间的交互,降低了系统的耦合性,但可能导致中介者自身变得复杂。在对象交互复杂且需要提高复用性的场景下,该模式提供了解决思路,但在多对多交互时需谨慎使用,以免过度设计。
摘要由CSDN通过智能技术生成

A:“我想租房,价位1500左右。”

中介:“好的,我这边有房源。什么时候过来看看,价钱划算。”

B:“我这边有闲置房间,想租出去,2000以上。”

中介:“可以的,我这边有客户。价钱好商量。”

中介---A:“房东B说了,低于2000不可以。”

中介---B:“客户A说了,高于18000,就太高了,不想考虑。”

......

尽管讲一个系统分割成所需对象,通常可以增加其复用性。但是对象间相互连接的激增,会降低其复用性。尤其是大量链接,会使得系统耦合性增加,对系统的改动,将会变得复杂和困难。这时可以考虑中介者模式。

中介者不参与实际声明,只负责传递消息。优点:集中控制,降低各个对象间的耦合。缺点:集中控制,使得中介者变得复杂。如果系统出现了多对多交互复杂的对象群时,不要急于使用该模式,而是想想是不是系统设计上存在不合理。总的来说该模式相对比较鸡肋。

#pragma  once
#include<iostream>
#include<string>
using std::string;

class Country;
//中介者抽象
class UniteNations
{
public:
	virtual void declare(string messasge ,const Country* country){ }
	virtual ~UniteNations(){}
protected:

};

//具体对象
class Country
{
public:
	 Country(UniteNations * unite) :m_unite(unite)
	{

	}
	virtual~Country(){}

protected:
	UniteNations * m_unite;
};


class USA : public Country
{
public:
	USA(UniteNations * unite) :Country(unite)
	{

	}

	void declare(string msg)
	{
		m_unite->declare(msg,this);
	}

	void getmsg(string msg)
	{
		printf("USA获得消息:%s\n", msg.c_str());
	}

};

class IRAQ : public Country
{
public:
	IRAQ(UniteNations * unite) :Country(unite)
	{

	}

	void declare(string msg)
	{
		m_unite->declare(msg, this);
	}

	void getmsg(string msg)
	{
		printf("IRAQ获得消息:%s\n", msg.c_str());
	}

};

//具体中介者
class UniteSecurityCouncil :public UniteNations
{
public:
	void setUSA(USA *usa)
	{
		m_usa = usa;
	}

	void setIRAQ(IRAQ *iraq)
	{
		m_iraq = iraq;
	}


	void declare(string messasge, const Country* country)
	{
		if (country==m_usa)
		{
			m_iraq->getmsg(messasge);
		}
		else
		{
			m_usa->getmsg(messasge);
		}
	}
private:
	USA *m_usa;
	IRAQ *m_iraq;
};


int main()
{
	UniteSecurityCouncil unsc;

	USA usa(&unsc);
	IRAQ iraq(&unsc);

	unsc.setUSA(&usa);
	unsc.setIRAQ(&iraq);

	usa.declare("把石油给我,否则发动战争!");
	iraq.declare("艹,你以为老子威胁大的?");

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值