意图:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
一般来说,只有对于那种同事类之间是网状结构的关系,才会考虑使用中介者模式。可以将网状结构变为星状结构,使同事类之间的关系变的清晰一些。
class Mediator { public:Mediator(){}~Mediator(){}virtual void Notify() = 0; };class Colleague { public:Colleague(Mediator* mediator){this->mediator = mediator;}virtual ~Colleague(){}protected:Mediator* mediator; };class ColleagueProvidor: public Colleague { public:ColleagueProvidor(Mediator* mediator): Colleague(mediator){}~ColleagueProvidor(){}void ChangeProvidor(){cout<<"ColleagueProvidor::ChangeProvidor()"<<endl;mediator->Notify();} };class ColleagueConsumer: public Colleague { public:ColleagueConsumer(Mediator* mediator): Colleague(mediator){}~ColleagueConsumer(){}void ChangeConsumer(){cout<<"ColleagueConsumer::ChangeConsumer()"<<endl;} };class ConcreteMediator: public Mediator { public:ConcreteMediator(){}~ConcreteMediator(){}void Introduce(ColleagueProvidor* providor, ColleagueConsumer* consumer){this->providor = providor;this->consumer = consumer;}void Notify(){consumer->ChangeConsumer();}private:ColleagueProvidor* providor;ColleagueConsumer* consumer; };