中介者模式
中介者模式(Mediator Pattern)是用來降低多個對象和類之間的通信複雜性。這種模式提供了一箇中介類,該類通常處理不同類之間的通信,並支持鬆耦合,使代碼易於維護。中介者模式屬於行爲型模式。
介紹
意圖:用一箇中介對象來封裝一系列的對象交互,中介者使各對象不需要顯式地相互引用,從而使其耦合鬆散,而且可以獨立地改變它們之間的交互。
主要解決:對象與對象之間存在大量的關聯關係,這樣勢必會導致系統的結構變得很複雜,同時若一個對象發生改變,我們也需要跟蹤與之相關聯的對象,同時做出相應的處理。
何時使用:多個類相互耦合,形成了網狀結構。
如何解決:將上述網狀結構分離爲星型結構。
關鍵代碼:對象 Colleague 之間的通信封裝到一個類中單獨處理。
應用實例: 1、中國加入 WTO 之前是各個國家相互貿易,結構複雜,現在是各個國家通過 WTO 來互相貿易。 2、機場調度系統。 3、MVC 框架,其中C(控制器)就是 M(模型)和 V(視圖)的中介者。
優點: 1、降低了類的複雜度,將一對多轉化成了一對一。 2、各個類之間的解耦。 3、符合迪米特原則。
缺點:中介者會龐大,變得複雜難以維護。
使用場景: 1、系統中對象之間存在比較複雜的引用關係,導致它們之間的依賴關係結構混亂而且難以複用該對象。 2、想通過一箇中間類來封裝多個類中的行爲,而又不想生成太多的子類。
注意事項:不應當在職責混亂的時候使用。
#include <iostream>
#include <string>
using namespace std;
class Country;
// 聯合國
class UniteNations
{
public:
virtual void declare(const char* pszMsg, Country* pCountry) = 0;
};
// 國家
class Country
{
public:
Country(UniteNations *pUnMediator)
{
this->m_pUnMediator = pUnMediator;
}
protected:
UniteNations *m_pUnMediator;
};
// 美國
class CountryUSA :public Country
{
public:
CountryUSA(UniteNations *pUnMediator):Country(pUnMediator)
{}
void Declare(const char*pszMsg)
{
cout << "美國軍方發佈信息: "<< pszMsg << endl;
m_pUnMediator->declare(pszMsg,this);
}
void GetMessage(const char*pszMsg)
{
cout <<"美國獲得對方信息 " << pszMsg << endl;
}
};
// 伊拉克
class CountryIraq :public Country
{
public:
CountryIraq(UniteNations *pUnMediator) :Country(pUnMediator)
{}
void Declare(const char*pszMsg)
{
cout << "伊拉克軍方發佈信息: " << pszMsg << endl;
m_pUnMediator->declare(pszMsg, this);
}
void GetMessage(const char*pszMsg)
{
cout << "伊拉克獲得對方信息 " << pszMsg << endl;
}
};
// 聯合國安理會
class UnitedNationsSecurityCouncil :public UniteNations
{
void declare(const char* pszMsg, Country* pCountry)
{
if (pCountry == pCountryUSA)
{
pCountryIraq->GetMessage(pszMsg);
}
else if (pCountry == pCountryIraq)
{
pCountryUSA->GetMessage(pszMsg);
}
}
public:
CountryUSA * pCountryUSA; // 美國
CountryIraq * pCountryIraq; // 伊拉克
};
int main()
{
UnitedNationsSecurityCouncil * pUNSC = new UnitedNationsSecurityCouncil();
CountryUSA *pUSA = new CountryUSA(pUNSC);
CountryIraq *pIRAQ = new CountryIraq(pUNSC);
pUNSC->pCountryUSA = pUSA;
pUNSC->pCountryIraq = pIRAQ;
pUSA->Declare("不準研發核武器,否則打你");
pIRAQ->Declare("美國去死");
cin.get();
return 0;
}