设计模式-行为-Mediator(中介者)模式

梦想游戏人
目录:
软件架构

对象之间的交互是很常见的需求了,如果系统非常大,对象很多,那么交互 通信起来的复杂度就大大增加了。需要

一个通信类来负责交互 这就是Meditator模式,还带来了系统间对象的松耦合

Mediator模式是一个很有用的模式,他把对对象间的通信封装到了一个类里面,把多对多的通信转换为一对多,降低了低通的复杂性,还具备系统解耦的特性,通过Mediator 各个colleague 就必须维护各自的通信对象和通信协议,降低了系统的耦合性,Mediator和colleague就可以相互独立的修改了。

还有个特点是集中控制,便于管理,也符合oop设计的 每个类单一职责和集中地原则

头文件
#pragma  once
#include "PublicHeaders.h"

class Mediator;


class Colleague
{
public:
	virtual void Action() = 0;

protected:
	Mediator *_mediator;
	friend class ConCreateMediator;
	virtual void Sync() = 0;

};

class ConCreateColleagueA :public Colleague
{
public:
	ConCreateColleagueA(Mediator*m);
	virtual void Action()override;
private:

	virtual void Sync()override;
};

class ConCreateColleagueB :public Colleague
{
public:
	ConCreateColleagueB(Mediator*m);
	virtual void Action()override;
private:

	virtual void Sync()override;
};



class Mediator
{
public:
	virtual void IntroColleague(Colleague*a, Colleague *b) = 0;
	virtual void DoActionFromAtoB() = 0;
	virtual void DoActionFromBtoA() = 0;


protected:
	Colleague *colleague_A;
	Colleague *colleague_B;


};


class ConCreateMediator :public Mediator
{
public:
	virtual void IntroColleague(Colleague*a, Colleague *b)override;
	virtual void DoActionFromAtoB()override;
	virtual void DoActionFromBtoA()override;

};



void testMediator();




源文件
#include "Mediator.h"




ConCreateColleagueA::ConCreateColleagueA(Mediator*m)
{
	this->_mediator = m;
}
void ConCreateColleagueA::Action()
{
	this->_mediator->DoActionFromAtoB();
}


void  ConCreateColleagueA::Sync()
{
	cout << __FUNCTION__ << endl;
}


ConCreateColleagueB::ConCreateColleagueB(Mediator*m)
{
	this->_mediator = m;
}
void  ConCreateColleagueB::Action()
{
	this->_mediator->DoActionFromBtoA();
}

void ConCreateColleagueB::Sync()
{
	cout << __FUNCTION__ << endl;
}






void  ConCreateMediator::IntroColleague(Colleague*a, Colleague *b)
{
	this->colleague_A = a;
	this->colleague_B = b;
}
void ConCreateMediator::DoActionFromAtoB()
{
	colleague_B->Sync();
}
void  ConCreateMediator::DoActionFromBtoA()
{
	colleague_A->Sync();
}





void testMediator()
{
	ConCreateMediator* mediator = new ConCreateMediator;

	ConCreateColleagueA *a = new ConCreateColleagueA(mediator);
	ConCreateColleagueB *b = new ConCreateColleagueB(mediator);
	mediator->IntroColleague(a, b);

	a->Action();
	b->Action();
	a->Action();



}
Scroll Up