C++设计模式---中介者模式
中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式(Mediator)结构图:
Colleague叫做抽象同事类,而ConcreteColleague是具体同事类,每个具体同事只知道自己的行为,而不了解其他同事类的情况,但它们却都认识中介者对象,Mediator是抽象中介者,定义了同事对象到中介者对象的接口,ConcreteMediator是具体中介者对象,实现抽象方法,它需要知道所有具体同事类,并从具体同事接收消息,向具体同事对象发出命令。
Mediator类抽象中介者
class Mediator
{
public:
virtual void Send(String message, Colleague * colleague)=0;
};
//定义一个抽象的发送消息方法,得到同事对象和发送信息
Colleague类抽象同事类
class Colleague
{
protected:
Mediator * mediator;
public:
Colleague(Mediator * mediator)
{
this->mediator = mediator;
}
//构造方法,得到中介者对象
};
ConcreteMediator类 具体中介者类
class ConcreteMediator : public Mediator
{
private:
ConcreteColleague1 *colleague1;
ConcreteColleague2 *colleague2;
public:
void SetColleague1(Colleague * colleague)
{
colleague1 = colleague;
}
void SetColleague2(Colleague * colleague)
{
Colleague2 = colleague;
}
void Send(String message , Colleague * colleague)
{
if(colleague == colleague1)
{
colleague2->Notify(message);
}
else
{
colleague1->Notify(message);
}
}
//重写发送信息的方法,根据对象做出选择判断,通知对象
};
ConcreteColleague1和ConcreteColleague2等各种同事对象
class ConcreteColleague1 : public Colleague
{
public:
ConcreteColleague1(Mediator * mediator):Colleague(mediator){}
void Send(String message)
{
mediator->Send(message,this);
}
void Notify(String message)
{
cout<< “同事1都到信息:”<<message<<endl;
}
};
class ConcreteColleague2 : public Colleague
{
public:
ConcreteColleague2(Mediator * mediator):Colleague(mediator){}
void Send(String message)
{
mediator->Send(message,this);
}
void Notify(String message)
{
cout<< “同事2都到信息:”<<message<<endl;
}
};
客户端代码:
void main()
{
ConcreteMediator * m= new ConcreteMediator();
ConcreteColleague1 * c1 = new ConcreteColleague1(m);
ConcreteColleague2 * c2 = new ConcreteColleague2(m);
m->SetColleague1(c1);
m->SetColleague2(c2);
c1->Send(“吃过饭了么?”);
c2->Send(“没有呢,你打算请客?”);
}
由于有了Mediator,使得ConcreteColleague1和ConcreteColleague2在发送消息和接收信息时其实是通过中介者来完成的,这就减少了它们之间的耦合度。