设计模式——中介者模式_Mediator Pattern

中介者模式:

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicity, and it lets you vary their interaction independently. (用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变他们之间的交互


C++代码:

#ifndef __MEDIATOR__H__  
#define __MEDIATOR__H__  

#include <iostream>
using namespace std;

class ConcreteColleague1;
class ConcreteColleague2;

class Mediator {
public:
	virtual void DoSomething1() = 0;
	virtual void DoSomething2() = 0;

	ConcreteColleague1* GetC1() { return _pCC1; }
	ConcreteColleague2* GetC2() { return _pCC2; }

	void SetC1(ConcreteColleague1* pCC1) { _pCC1 = pCC1; }
	void SetC2(ConcreteColleague2* pCC2) { _pCC2 = pCC2; }


protected:
	ConcreteColleague1* _pCC1;
	ConcreteColleague2* _pCC2;
};

class ConcreteMediator : public Mediator {
	void DoSomething1() {
		cout << "中介者介入处理业务DoSomething1()" << endl;
		_pCC1->SelfMethod1();
		_pCC2->SelfMethod2();
	}
	void DoSomething2() {
		cout << "中介者介入处理业务DoSomething2()" << endl;
		_pCC1->SelfMethod1();
		_pCC2->SelfMethod2();
	}
};


class Colleague {
public:
	Colleague(Mediator* pM): _pM(pM) { }
	virtual ~Colleague() = 0;
protected:
	Mediator* _pM;
};

class ConcreteColleague1 : public Colleague {
public:
	void SelfMethod1() { cout << "ConcreteColleague1处理自身业务"<< endl; }
	void DepMethod1()  { 
		cout << "ConcreteColleague1依赖终结者处理业务"<< endl;
		_pM->DoSomething1();
	}
};

class ConcreteColleague2 : public Colleague {
public:
	void SelfMethod2() { cout << "ConcreteColleague2处理自身业务"<< endl; }
	void DepMethod2()  { 
		cout << "ConcreteColleague2依赖终结者处理业务"<< endl;
		_pM->DoSomething2();
	}
};

#endif


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值