中介者模式
一、中介者模式的概念
中介者模式是行爲型模式之一,中介者模式(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、中介者類可能會變得龐大,維護比較困難。
能力有限,如有錯誤,多多指教。。。