中介者模式:用一个中介对象来封装一些列对象的交互。中介者使个对象不需要显式地向后引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
中介者降低了各个具体类之间的耦合,使其独立开来,但是随着具体类的增加,会变得很复杂。
适用于一组对象以定义良好但复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。
注意:中介者在传递消息时需要判断当前参数所指的对象的类型。
中介者模式范例:
#include <iostream>
#include <string>
using namespace std;
class Colleague;
class Mediator
{
public:
virtual void Send(string message,Colleague* colleague) = 0;
};
class Colleague
{
public:
Colleague(Mediator* mediator)
{
this->mediator = mediator;
}
protected:
Mediator* mediator;
};
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;
}
};
class ConcreteMediator : public Mediator
{
public:
void setConcreteColleague1(ConcreteColleague1* value)
{
colleague1 = value;
}
void setConcreteColleague2(ConcreteColleague2* value)
{
colleague2 = value;
}
void Send(string message,Colleague* colleague)
{
if(colleague == colleague1)
colleague2->Notify(message);
else
colleague1->Notify(message);
}
private:
ConcreteColleague1* colleague1;
ConcreteColleague2* colleague2;
};
int main()
{
ConcreteMediator* M = new ConcreteMediator();
ConcreteColleague1* C1 = new ConcreteColleague1(M);
ConcreteColleague2* C2 = new ConcreteColleague2(M);
M->setConcreteColleague1(C1);
M->setConcreteColleague2(C2);
C1->Send("你好啊");
C2->Send("how are you");
return 0;
}
中介者实例:
#include <iostream>
#include <string>
using namespace std;
class Friend;
class Mediator
{
public:
virtual void Send(string message,Friend* ffriend) = 0;
};
class Friend
{
public:
Friend(Mediator* mediator)
{
this->mediator = mediator;
}
protected:
Mediator* mediator;
};
class xiaoGao : public Friend
{
public:
xiaoGao(Mediator* mediator) : Friend(mediator) {}
void Send(string message)
{
mediator->Send(message,this);
}
void Notify(string message)
{
cout << "小高得到消息:" << message << endl;
}
};
class xiaoChen : public Friend
{
public:
xiaoChen(Mediator* mediator) : Friend(mediator) {}
void Send(string message)
{
mediator->Send(message,this);
}
void Notify(string message)
{
cout << "小陈得到消息:" << message << endl;
}
};
class WeChat : public Mediator
{
public:
void setxiaoGao(xiaoGao* value)
{
friend1 = value;
}
void setxiaoChen(xiaoChen* value)
{
friend2 = value;
}
void Send(string message,Friend* ffriend)
{
if(ffriend == friend1)
friend2->Notify(message);
else
friend1->Notify(message);
}
private:
xiaoGao* friend1;
xiaoChen* friend2;
};
int main()
{
WeChat* M = new WeChat();
xiaoGao* C1 = new xiaoGao(M);
xiaoChen* C2 = new xiaoChen(M);
M->setxiaoGao(C1);
M->setxiaoChen(C2);
C1->Send("在吗?");
C2->Send("不在!");
return 0;
}