设计模式---行为类型---中介者

1、意图

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

2、动机

面向对象设计鼓励将行为分布到各个对象中。这种分布可能会导致对象间有许多连接。在最坏的情况下,每一个对象都知道其他所有对象。

虽然将一个系统分割成许多对象通常可以增强可复用性,但是对象间相互连接的激增又会降低其可复用性。大量的相互连接使得一个对象似乎不太可能在没有其他对象的支持下工作---系统表现为一个不可分割的整体。而且,对系统的行为进行任何较大的改动都十分困难,因为行为被分布在许多对象中。结果是,你可能不得不定义很多子类以定制系统的行为。

3、适用性

在下列情况下使用中介者模式:

1)一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解。

2)一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。

3)想定制一个分布在多个类中的行为,而又不想生成太多的子类。

4、C++实例

// Test.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <atlstr.h>
#include <iostream>
#include <string>
using namespace std;
class Country;
class UnitedNations
{
public:
	virtual void Declare(string message,Country* colleague)
	{

	}
};
class Country
{
protected:
	UnitedNations* m_pmediator;
public:
	Country(UnitedNations* mediator)
	{
		this->m_pmediator=mediator;
	}
};
class USA:public Country
{
public:
	USA(UnitedNations* mediator):Country(mediator)
	{

	}
	/*virtual*/ void Declare(string message)//virtual 
	{
		m_pmediator->Declare(message,this);
	}
	void GetMessage(string message)
	{
		cout<<"美国获得对方信息:"<<message<<endl;
	}
};
class Iraq:public Country
{
public:
	Iraq(UnitedNations* mediator):Country(mediator)
	{

	}
	void Declare(string message)//virtual 
	{
		m_pmediator->Declare(message,this);
	}
	void GetMessage(string message)
	{
		cout<<"伊拉克获得对方信息:"<<message<<endl;
	} 
};
class UnitedNationsSecurityCouncil:public UnitedNations
{
public:

	USA* m_pcolleague1;

	Iraq* m_pcolleague2;

public:

	/*virtual*/ void Declare(string message,Country* colleague)
	{
		if (colleague==m_pcolleague1)
		{
			m_pcolleague2->GetMessage(message);
		}
		else
		{
			m_pcolleague1->GetMessage(message);
		}
	}

};

int _tmain(int argc, _TCHAR* argv[])
{
	UnitedNationsSecurityCouncil* pUNSC=new UnitedNationsSecurityCouncil;
	USA* pC1=new USA(pUNSC);
	Iraq* pC2=new Iraq(pUNSC);

	pUNSC->m_pcolleague1=pC1;
	pUNSC->m_pcolleague2=pC2;


	pC1->Declare("不准研制核武器,否则要发动战争!");
	pC2->Declare("我们没有核武器,也不怕侵略");
	delete(pUNSC);
	delete(pC1);
	delete(pC2);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值