设计模式之中介者模式-无中介,该多好!

一、中介者模式的概念

中介者模式是行为型模式之一,中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性,它提供了一个中介类,通过中介类处理不同类之间的通信,并支持松耦合,使代码易于维护。

二、中介者模式使用场景

系统中用一个中介对象,封装一系列对象的交互行为,中介者协调着各个对象的相互作用,从而实现解耦合,独立的改变各个对象之间的交互。

三、中介者模式构建方法

1、中介者抽象类(Mediator)

中介者抽象类给中介者具体类提供统一的共同接口和方法。

2、中介者具体类(ConcreteMediator)

中介者具体类继承中介者抽象类,用于实现中介者抽象父类中的共同接口和方法,所有的关联类都要通过中介类进行交互。

3、关联类的抽象类(Colleague,关联又称为同事,本文以关联称谓)

关联类的抽象父类,给具体关联类提供统一的共同接口和方法。

4、关联类的具体类(ConcreteColleague)

关联类的具体类继承关联类的抽象类,用于实现关联类的抽象父类中的共同接口和方法。

四、中介者模式的示例

// MediatorPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>

using namespace std;

#define DELETE_PTR(p) {if(p!=nullptr){delete (p); (p)=nullptr;}}


class User;
// 中介者抽象类-基站
class BaseStation
{
public:
	virtual void callPhone(User *pUser) = 0;
	virtual void setUserOne(User *pUserOne) = 0;
	virtual void setUserTwo(User *pUserTwo) = 0;
};

// 中介者具体实现类-通讯基站
class CommunicationStation : public BaseStation
{
public:
	void setUserOne(User *pUserOne)
	{
		m_pUserOne = pUserOne;
	}

	void setUserTwo(User *pUserTwo)
	{
		m_pUserTwo = pUserTwo;
	}

	void callPhone(User *pUser)
	{
		if (pUser == m_pUserOne)
		{
			cout << "UserOne call phone UserTwo." << endl; // 用户1给用户2打电话
		}
		else
		{
			cout << "UserTwo call phone UserOne." << endl; // 用户2给用户1打电话
		}
	}

private:
	User *m_pUserOne;
	User *m_pUserTwo;
};

// 关联(同事)类的抽象类-用户
{
public:
	User(BaseStation* pBaseStation)
	{
		m_pBaseStation = pBaseStation;
	}
	virtual void callPhone() = 0;

protected:
	BaseStation *m_pBaseStation;
};

// 关联类的具体类-用户1
class UserOne : public User
{
public:
	UserOne(BaseStation* pComStation) : User(pComStation) {}

	void callPhone()
	{
		m_pBaseStation->callPhone(this);
	}
};

// 关联类的具体类-用户2
class UserTwo : public User
{
public:
	UserTwo(BaseStation* pComStation) : User(pComStation) {}

	void callPhone()
	{
		m_pBaseStation->callPhone(this);
	}
};

int main()
{
	cout << "--------------中介者模式---------------" << endl;

	BaseStation *pBaseStation = new CommunicationStation();
	User *pUserOne = new UserOne(pBaseStation);
	User *pUserTwo = new UserTwo(pBaseStation);
	
	pBaseStation->setUserOne(pUserOne);
	pBaseStation->setUserTwo(pUserTwo);
	pUserOne->callPhone();
	pUserTwo->callPhone();

	DELETE_PTR(pUserOne);
	DELETE_PTR(pUserTwo);
	DELETE_PTR(pBaseStation);

    std::cout << "Hello World!\n";
	getchar();
}

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

五、中介者模式的优缺点

优点:

1、降低了类的复杂度,将类的关系有一对多转化成一对一的关系,符合类的最小设计原则。
2、对关联的对象进行集中的控制。
3、对类进行解耦合,明确各个类之间的相互关系。

缺点:

1、中介者类可能会变得庞大,维护比较困难。

能力有限,如有错误,多多指教。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章