设计模式读书笔记:Mediator(中介者)
2015-07-10 21:04:45
意图:
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Mediator
Colleague
namespace NS_MEDIATOR {
class Colleague {
public:
Colleague() {}
virtual ~Colleague() {}
};
} /* namespace NS_MEDIATOR */
ConcreteColleague1
namespace NS_MEDIATOR {
class ConcreteColleague1 {
public:
ConcreteColleague1() {}
virtual ~ConcreteColleague1() {}
bool needPrint(void) { return true; }
};
} /* namespace NS_MEDIATOR */
ConcreteColleague2
#include <iostream>
namespace NS_MEDIATOR {
class ConcreteColleague2 {
public:
ConcreteColleague2() {}
virtual ~ConcreteColleague2() {}
void printSelf(void)
{
std::cout << "ConcreteColleague2" << std::endl;
}
};
} /* namespace NS_MEDIATOR */
Mediator
namespace NS_MEDIATOR {
class Mediator {
public:
Mediator() {}
virtual ~Mediator() {}
};
} /* namespace NS_MEDIATOR */
ConcreteMediator
#include "ConcreteColleague1.h"
#include "ConcreteColleague2.h"
namespace NS_MEDIATOR {
class ConcreteMediator {
public:
ConcreteMediator()
{
cc1 = new ConcreteColleague1();
cc2 = new ConcreteColleague2();
}
virtual ~ConcreteMediator()
{
delete cc1;
delete cc2;
}
void doSomething(void)
{
if (cc1->needPrint())
cc2->printSelf();
}
private:
ConcreteColleague1 *cc1;
ConcreteColleague2 *cc2;
};
} /* namespace NS_MEDIATOR */
main
#include "Mediator/ConcreteMediator.h"
using namespace NS_MEDIATOR;
int main(void)
{
/*
* 这个设计模式估计大家都经常用,设想一下,我有若干个类A,B,C,D,我想组合它们实现实现不同的功能
* 譬如ABC实现功能,BCD又实现另外一个功能等等,我把这些实现用类封装起来,它就算是一个中介者了
* 为什么要有Colleague及Mediator基类,你直接看书中的场景,很好理解
*/
ConcreteMediator cm;
cm.doSomething();
}
附加: