设计模式一日一练:中介者模式(Mediator)

时间:2023-03-08 15:24:33
设计模式一日一练:中介者模式(Mediator)

Mediator模式,用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

比较典型的例子是联合国、QQ群等。比如,如果中国有事需要通知世界各国,可以通过联合国这一个机构,QQ群可以接收并发布每个成员的消息。


/*
* file: Mediator.h
* brief: Created by night at 2016.12.07
*/ #ifndef __MEDIATOR_H__
#define __MEDIATOR_H__ #include <list>
#include <iostream> using namespace std; class Nation;
class Mediator {
public:
virtual void Send(Nation* member, const char* msg) = 0;
}; class UnitedNationsMediator : public Mediator {
public:
UnitedNationsMediator() { } void Register(Nation* member) { members.push_back(member); } void Send(Nation* member, const char* msg); list<Nation*> members;
}; class Nation {
public:
Nation(const char* sname, Mediator* m) : name(sname), mediator(m) { }
void Send(const char* msg) { mediator->Send(this, msg); }
void Notify(const char* sender, const char* msg) { cout << name << "\t<-- " << sender << ":\t" << msg << endl; } const char* name; protected:
Mediator* mediator;
}; class China : public Nation
{
public:
China(const char* sname, Mediator* m): Nation(sname, m) { }
}; class USA : public Nation
{
public:
USA(const char* sname, Mediator* m) : Nation(sname, m) { }
}; class England : public Nation
{
public:
England(const char* sname, Mediator* m) : Nation(sname, m) { }
}; void TestMediator(); #endif

/*
* file: Mediator.cpp
* brief: Created by night at 2016.12.07
*/ #include "Mediator.h" void UnitedNationsMediator::Send(Nation* member, const char* msg) {
for (list<Nation*>::iterator itr = members.begin(); itr != members.end(); itr++) {
(*itr)->Notify(member->name, msg);
}
} void TestMediator()
{
UnitedNationsMediator* mediator = new UnitedNationsMediator();
China* china = new China("China", mediator);
mediator->Register(china); USA* usa = new USA("USA", mediator);
mediator->Register(usa); England* england = new England("England", mediator);
mediator->Register(england); china->Send("This is from China!");
cout << endl; usa->Send("This is from USA!");
cout << endl; // destroy ...
delete mediator;
mediator = NULL;
delete china;
china = NULL;
delete usa;
usa = NULL;
delete england;
england = NULL;
}

输出结果:

China   <-- China:      This is from China!
USA <-- China: This is from China!
England <-- China: This is from China! China <-- USA: This is from USA!
USA <-- USA: This is from USA!
England <-- USA: This is from USA!

引用

  1. 《设计模式:可复用面向对象软件的基础》