中介者模式(Mediator)
中介者模式(Mediator):用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
美国和伊拉克之间的对话都是通过联合国安理会作为中介来完成的。
#include <iostream>
using namespace std;
#define SAFE_DELETE(p) {if(p){delete p; p = nullptr;}}
class Country;
//联合国机构
class UnitedNations {
public:
virtual void Declare(string message, Country* colleague){}
};
//国家类 相当于Colleage类
class Country {
protected:
UnitedNations* mediator = nullptr;
public:
Country(UnitedNations* mediator) {
this->mediator = mediator;
}
};
//美国
class USA :public Country{
public:
USA(UnitedNations* mediator):Country(mediator){}
void Declare(string message) {
mediator->Declare(message, this);
}
void GetMessage(string message) {
cout << "美国获得对方信息:" << message << endl;
}
};
//伊拉克
class Iraq :public Country {
public:
Iraq(UnitedNations* mediator) :Country(mediator) {}
void Declare(string message) {
mediator->Declare(message, this);
}
void GetMessage(string message) {
cout << "伊拉克获得对方信息:" << message << endl;
}
};
//联合国安理会 相当于ConcreteMediator类
class UnitedNationsSecurityCouncil :public UnitedNations {
private:
USA* colleague1 = nullptr;
Iraq* colleague2 = nullptr;
public:
void SetUSAColleague1(USA* colleague){
colleague1 = colleague;
}
void SetIraqColleague2(Iraq* colleague){
colleague2 = colleague;
}
void Declare(string message, Country* colleague) {
if (colleague == colleague1)
colleague2->GetMessage(message);
else
colleague1->GetMessage(message);
}
};
//客户端
void test01() {
UnitedNationsSecurityCouncil* UNSC = new UnitedNationsSecurityCouncil();
USA* c1 = new USA(UNSC);
Iraq* c2 = new Iraq(UNSC);
UNSC->SetUSAColleague1(c1);
UNSC->SetIraqColleague2(c2);
c1->Declare("不准研制核武器,否则要发动战争!");
c2->Declare("我们没有核武器,也不怕侵略。");
SAFE_DELETE(c2);
SAFE_DELETE(c1);
SAFE_DELETE(UNSC);
}
int main() {
test01();
return 0;
}