Mediator
原创
©著作权归作者所有:来自51CTO博客作者wx6405b2c488d4e的原创作品,请联系作者获取转载授权,否则将追究法律责任
Mediator模式主要是用于对象间的通信,我们知道任何对象都不能是单独存在的,通信对象之间的通信,需要有个执行体,如果是对象直接去进行通信势必会增加对象的负担,
除此之外,还会增加对象之间的耦合度,要有一个专门的类进行通信,降低系统的复杂性,也是一种更为艺术的做法,下面是Mediator的示意图
Mediator模式,其实不过就是在Mediator类当中记录下,要进行通信类的指针,然后通过指针,对这两个类对象进行某种操作,即为通信:
#include"string"
#include"iostream"
using namespace std;
class Mediator;
class Colleage
{
public:
Colleage(Mediator*tmp)
{
_mdt=tmp;
}
virtual string getState() =0;
virtual void setState(string state)=0;
virtual void Action()=0;
private:
Mediator*_mdt;
};
class ConcreteColleageA:public Colleage
{
public:
ConcreteColleage(Mediator*tmp):Colleage(tmp)
{;}
void setState(string st)
{_st=st;}
string getState()
{return _st; }
void action()
{_mdt->DoActionFromAtoB();}
private:
string _st;
};
class ConcreteColleageB:public Colleage
{
public:
ConcreteColleageB(Mediator*tmp):Colleage(tmp)
{;}
void setState(string st)
{_st=st;}
string getState()
{return _st;}
void action()
{_mdt->DoActionFromBtoA();}
private:
string _st;
};
class Mediator
{
public:
Mediator()
{;}
setMediator(Colleage*tmpa,Colleage*tmpb)
{this->tmpa=tmpa;
this->tmpb=tmpb;}
void DoActionFromAtoB()
{tmpa->setState(tmpb->getState());
}
void DoActionFromBtoA()
{
tmpa->setState(tmpb->getState()) ;
}
private:
Colleage*tmpa;
Colleage*tmpb;
};
int main()
{
Mediator*m=new Mediator();
ConcreteColleageA*c1=new ConcreteColleageA();
ConcreteColleageB*c2=new ConcreteColleageB();
m->setMediator(c1,c2);
c1->setState("old");
c2->setState("new");
c1->action();
cout<getState()<<endl;
cout<getState()<
action();
cout<getState()<<endl;
cout<getState()<<endl;
}
其实这也算是bridge模式的一种应用吧,毕竟是对象组合的方式