中介者模式(Mediator)用一个中介对象封装了一系列对象的交互联系,使它们不需要相互了解就可以协同工作。中介者模式在存在大量需要相互通信对象的系统中特别有用,因为对象数量的增加会使对象间的联系非常复杂,整个系统变得难以理解难以改动。这时中介者可以把这些对象解耦,每个对象只需要与中介对象通信,中介对象集中了控制逻辑,降低了系统的通信复杂度。
中介者模式与观察者模式是相互竞争的模式,通常观察者模式比中介者模式更容易生成可复用的对象,中介者模式如果使用不当很容易导致中介对象过度复杂,抵消了模式带来的好处。
GOOD:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显示的相互引用,从而降低耦合;而且可以独立地改变它们之间的交互。
RES:http://hi.baidu.com/xuehuo_0411/item/a2571a192ae4d6fe65eabfd1
C++实现:
#include <iostream>
#include <string>
using namespace std;
class Colleague;
// 中介者类
class Mediator
{
public:
virtual void Send(string message, Colleague* col) = 0;
};
// 同事类
class Colleague
{
public:
Colleague(Mediator* temp) { mediator = temp; }
protected:
Mediator* mediator;
};
// 同事一
class ColleagueOne : public Colleague
{
public:
ColleagueOne(Mediator* media) : Colleague(media) {}
void Send(string strMessage) { mediator->Send(strMessage, this); }
void Notify(string strMessage) { cout << "同事一获得了消息:" << strMessage << endl; }
};
// 同事二
class ColleagueTwo : public Colleague
{
public:
ColleagueTwo(Mediator* media) : Colleague(media) {}
void Send(string strMessage) { mediator->Send(strMessage, this); }
void Notify(string strMessage) { cout << "同事二获得了消息:" << strMessage << endl; }
};
// 具体中介者类
class ConcreteMediator : public Mediator
{
public:
ColleagueOne* colOne;
ColleagueTwo* colTwo;
virtual void Send(string message, Colleague* col);
};
void ConcreteMediator::Send(string message, Colleague* col)
{
if (col == colOne)
{
colTwo->Notify(message);
}
else
{
colOne->Notify(message);
}
}
int main()
{
ConcreteMediator* m = new ConcreteMediator();
// 让同事认识中介
ColleagueOne* colOne = new ColleagueOne(m);
ColleagueTwo* colTwo = new ColleagueTwo(m);
// 让中介认识具体的同事类
m->colOne = colOne;
m->colTwo = colTwo;
colOne->Send("吃饭了吗?");
colTwo->Send("还没吃,你请啊?");
return 0;
}