(二十一)中介者模式

来源:互联网 发布:局域网共享端口 编辑:程序博客网 时间:2024/05/16 19:00


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

UML:

源码:

// Mediator.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <string>using namespace std;class Country;//联合国机构class UnitedNations{public:virtual void Declare(string message, Country *colleague) = 0;};//国家class Country{protected:UnitedNations *mediator;public:Country(UnitedNations *mediator){this->mediator = mediator;}virtual void Declarep(string message){};};//美国class USA : public Country{public:USA(UnitedNations *mediator): Country(mediator){}//声明public:void Declare(string message){mediator->Declare(message, this);}//获得消息void GetMessage(string message){cout << "美国获得对方信息:" << message << endl;}};//伊拉克class Iraq : public Country{public:Iraq(UnitedNations *mediator): Country(mediator){}//声明public:void Declare(string message){mediator->Declare(message, this);}//获得消息void GetMessage(string message){cout << "伊拉克获得对方信息:" << message << endl;}};//联合国安全理事会class UnitedNationsSecurityCouncil : public UnitedNations{public:USA *colleague1;Iraq *colleague2;public:void Declare(string message, Country *colleague){USA *p = dynamic_cast<USA*>(colleague);if (p){colleague2->GetMessage(message);}else{colleague1->GetMessage(message);}}};int _tmain(int argc, _TCHAR* argv[]){UnitedNationsSecurityCouncil *UNSC = new UnitedNationsSecurityCouncil();USA *c1 = new USA(UNSC);Iraq *c2 = new Iraq(UNSC);UNSC->colleague1 = c1;UNSC->colleague2 = c2;c1->Declare("不准研制核武器,否则要发动战争!");c2->Declare("我们没有核武器,也不怕侵略。");return 0;}

输出:

上例中,引入了《大话设计模式》的例子,由于国家非常多,这些国家相当于独立的但是关系复杂的类,可以通过联合国这个中介来解决,比如美国和伊拉克有发生战争的危机,就需要通过联合国的安理会来解决。

优点:
1.Mediator的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator
2.由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。

缺点:
1.由于concretemediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。

应用场景:
中介者模式一般应用于一组对象时以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。


0 0
原创粉丝点击