中介者嘛,大家都应该知道是什么意思。比如联合国,其实就是一个中介机构,为多个国家提供一个交流平台,比如美帝说“伊拉克你要在搞核武器,我就揍你”,但是和伊拉克言语不通,需要联合国来传达,同样伊拉克发布的信息需要联合国传达给美国。这种模式就是中介者模式。
中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,因而使其耦合松散,而且可以独立地改变它们之间的交互。
Colleague叫做抽象同事类,比如上文中的国家类就是一个抽象类,而ConcreteColleague是具体同事类,每个具体同时只知道自己的行为,而不了解其他同事类的情况,但是他们却都认识中介者对象,Mediator是抽象中介者,定义了同事对象到中介者对象的接口,ConcreteMediator是具体中介者对象,实现抽象类的方法,需要知道所有具体同事类,并从具体同事类接收消息,向具体同时对象发出命令。
中介者优点:Mediator的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator;其次,由于吧对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装到一个对象中,这样关注的对象就从对象各自本身的行为转移到他们的交互中来,也就是站在一个更宏观的角度去看系统。
缺点:由于ConcreteMediator控制了集中化,于是就把交互复杂性为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
应用场景:中介者模式一般应用于一组对象以定义良好但是交互复杂的方式进行通信的机会。
#include<iostream>
#include<string>
using namespace std;
class Country;
class UniteNations//中介的抽象类
{
public:
virtual void declare(string message, Country *colleague) = 0;//信息发布平台,colleague在这里发布信息
};
class Country
{
protected:
UniteNations *mediator;//每一个对象都需要认识一个中介者
public:
Country(UniteNations *mediator)
{
this->mediator = mediator;
}
};
class USA :public Country
{
public:
USA(UniteNations *mediator) :Country(mediator)
{}
void declare(string message)//发布信息
{
cout << "美发布信息: " << message << endl;
mediator->declare(message, this);//看到了吗,USA不直接发布信息,调用Mediator的信息发布平台
}
void getMessage(string message)//接收信息
{
cout << "美国获得对方信息: " << message << endl;
}
};
class Iraq :public Country
{
public:
Iraq(UniteNations *mediator) :Country(mediator)
{}
void declare(string message)
{
cout << "伊拉克发布信息: " << message << endl;
mediator->declare(message, this);
}
void getMessage(string message)
{
cout << "伊拉克获得对方信息: " << message << endl;
}
};
class UnitedNationsSecurityCouncil :public UniteNations
{
public:
USA *usa;//既然是中介嘛,就要知道双方的
Iraq *iraq;
void declare(string message, Country *colleague)//colleague来这里发布信息了
{
if (colleague == usa)
{
iraq->getMessage(message); //如果是美国人发布了信息,则把信息送给iraq
}
else
{
usa->getMessage(message);//如果是伊拉克人发布了信息,则把信息发送给美国
}
}
};
int main()
{
UnitedNationsSecurityCouncil *unsc = new UnitedNationsSecurityCouncil();
USA *c1 = new USA(unsc);
Iraq *c2 = new Iraq(unsc);
unsc->usa = c1;
unsc->iraq = c2;
c1->declare("不准开发核武器,否则揍你!");//美国人发布信息
c2->declare("我们没有核武器,也不怕你!");//伊拉克人发布信息
delete unsc;
delete c1;
delete c2;
return 0;
}