概念:
用一个中介对象来封装一系列的对象交互,中介者使用各对象不需要显示相互引用,从而降低耦合,而且可以独立地改变他们之间的交互。
适用于:用一个中介对象,封装一系列对象的交换,中介者是各个对象不需要显示的相互作用,从而实现了耦合松散,而且可以独立的改变他们之间的交换。
模式有点:
1.将系统按照功能分割成更小的对象,符合类的最小设计原则,
2,对关联对象的集中控制
结构图:
需求:
现有男孩和女孩,男孩通过中介者发送“I Love My Girl”,女孩收到后通过中介者回复“I Love You Too”
实现;
class Person;
class Mediator{
private:
Person *pboy;
Person *pgirl;
public:
void set(Person *pb, Person *pg){
this->pboy = pb;
this->pgirl = pg;
}
void send(string msg, Person *t);
};
class Person{
protected:
Mediator *mediator;
public:
void set(Mediator *m){
this->mediator = m;
}
virtual void send(string msg) = 0;
virtual void receive(string msg)=0;
};
class Boy :public Person{
public:
void send(string msg){
cout << "男孩发送:" << msg << endl;
mediator->send(msg, this);
}
virtual void receive(string msg){
cout << "男孩收到:" << msg << endl;
}
};
class Girl :public Person{
public:
void send(string msg){
cout << "女孩发送:" << msg << endl;
mediator->send(msg, this);
}
virtual void receive(string msg){
cout << "女孩收到:" << msg << endl;
}
};
void Mediator::send(string msg, Person *t){
if (t != pboy){
pboy->receive(msg);
}
else{
pgirl->receive(msg);
}
}
客户端;
int main(void){
Mediator *mediator = new Mediator();
Boy *boy = new Boy();
Girl *girl = new Girl();
boy->set(mediator);
girl->set(mediator);
mediator->set(boy, girl);
boy->send("I Love My Girl");
girl->send("I Love You Too");
system("pause");
return 0;
}
运行结果;