标签:tco 相互 chapter ted 集中化 系统 cout space clu
中介者模式(Mediator): 用一个中介者对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
#include <iostream>
#include<vector>
#include<string>
#include<ctime>
using namespace std;
class Colleague;
class Mediator
{
public:
virtual void Send(string message, Colleague* colleagur) = 0;
};
class Colleague
{
protected:
Mediator* mediator;
public:
Colleague(Mediator* mediator_t)
{
mediator = mediator_t;
}
};
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
{
private:
ConcreteColleague1* colleague1;
ConcreteColleague2* colleague2;
public:
void setConcreteColleague1(ConcreteColleague1* colleague1_t) { colleague1 = colleague1_t; }
void setConcreteColleague2(ConcreteColleague2* colleague2_t) { colleague2 = colleague2_t; }
void Send(string message, Colleague* colleague)
{
if (colleague == colleague1)
colleague2->Notify(message);
else
colleague1->Notify(message);
}
};
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("没有,你打算请客么?");
system("pause");
return 0;
}
中介模式很容易在系统中应用,也很容易在系统中误用。当系统出现了‘多对多’交互复杂的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是不是合理。
中介者模式的优点首先是Mediator的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator。其次,由于把对象如何协作进行了抽象,将中介作为一个独立地概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到他们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
但是,由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
标签:tco 相互 chapter ted 集中化 系统 cout space clu
原文地址:https://www.cnblogs.com/wfcg165/p/12053825.html