中介者模式,就是用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式结构图
中介者模式基本代码
#include <iostream>
#include <string>
using namespace std;
class Colleague;
class Mediator {
public:
virtual void Send(string message, Colleague* colleague) = 0;
virtual ~Mediator() {}
};
class Colleague {
protected:
Mediator* mediator;
public:
Colleague(Mediator* m) { mediator = m; }
};
class ConcreteColleague1 : public Colleague {
public:
ConcreteColleague1(Mediator* m) : Colleague(m) {}
void Send(string message) {
mediator->Send(message, this);
}
void Notify(string message) {
cout << "ConcreteColleague1 received: " << message << endl;
}
};
class ConcreteColleague2 : public Colleague {
public:
ConcreteColleague2(Mediator* m) : Colleague(m) {}
void Send(string message) {
mediator->Send(message, this);
}
void Notify(string message) {
cout << "ConcreteColleague2 received: " << message << endl;
}
};
class ConcreteMediator : public Mediator {
private:
ConcreteColleague1* c1;
ConcreteColleague2* c2;
public:
void set(ConcreteColleague1* c) { c1 = c; }
void set(ConcreteColleague2* c) { c2 = c; }
void Send(string message, Colleague* colleague) {
if (colleague == c1) c2->Notify(message);
else c1->Notify(message);
}
};
int main() {
ConcreteMediator* m = new ConcreteMediator();
ConcreteColleague1* c1 = new ConcreteColleague1(m);
ConcreteColleague2* c2 = new ConcreteColleague2(m);
m->set(c1);
m->set(c2);
c1->Send("Hello"); // ConcreteColleague2 received: Hello
c2->Send("World"); // ConcreteColleague1 received: World
delete m;
delete c1;
delete c2;
return 0;
}
应用场景
中介者模式一般用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。
优点:
- Mediator减少了各个Colleague的耦合,使得可以独立地完成改变和复用各个Colleague类和Mediator;
- 由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注对象就从对象各自本身的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
缺点:
- 由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者变得比任何一个ConcreteColleague更复杂。