您的位置:首页 > 编程语言 > C语言/C++

设计模式---中介者模式(C++实现)

2017-03-13 12:21 387 查看
/***********************************************************************************************

中介者模式:
顾名思义,就是找了个中间人完成两个类的对象的交互

适用于:
用一个中介对象,封装一些列对象(同事)的交换,中介者是各个对象不需要显示的相互作用,从而实现了

耦合松散,而且可以独立的改变他们之间的交换。

实现方法:
中介者(还有陌生人的基类指针)   陌生人(含有中介者的基类指针)

当陌生人1发送消息的时候,调用的是中介者的发送函数,而中介者对发消息的指针进行判断在决定调用谁的函数

当陌生人2发送消息的时候,调用的是中介者的发送函数,而中介者对发消息的指针进行判断在决定调用谁的函数
陌生人都有中介者的统一接口

************************************************************************************************/

#include <iostream>

#include <string>

#include <vector>

using namespace std;

class Colleague;

class Mediator

{//抽象中介者类

public:
virtual void Send(string message, Colleague* col) = 0;

};

class Colleague

{//同事类

protected:
Mediator* mediator;

public:
Colleague(Mediator* temp)
{mediator = temp;}

};

class Colleague1 : public Colleague

{//同事一

public:
Colleague1(Mediator* media) : Colleague(media){}
void Send(string strMessage)
{ mediator->Send(strMessage, this);
}
void Notify(string strMessage)
{ cout << "同事一获得了消息" << strMessage << endl;
}

};

class Colleague2 : public Colleague

{//同事二

public:
Colleague2(Mediator* media) : Colleague(media){}
void Send(string strMessage)
{ mediator->Send(strMessage, this);}
void Notify(string strMessage)
{ cout << "同事二获得了消息" << strMessage << endl;
}

};

class ConcreteMediator : public Mediator

{//具体中介者类

public:
Colleague1 * col1;
Colleague2 * col2;
virtual void Send(string message, Colleague* col)
{
if (col == col1)//就是说如果传来的第1个同时发送的消息,那么我就调同事2的函数
col2->Notify(message);
else //就是说如果传来的第2个同时发送的消息,那么我就调同事1的函数
col1->Notify(message);
}

};

int main()

{
ConcreteMediator * m = new ConcreteMediator();//中间人要拥有同事类的基类指针才能操作,同事类
Colleague1* col1 = new Colleague1(m);
//让同事认识中介,实际就是得到具体中介者对象的指针  在同事类的基类中含有中介者的指针变量
Colleague2* col2 = new Colleague2(m);
//让同事认识中介,实际就是得到具体中介者对象的指针  在同事类的基类中含有中介者的指针变量
m->col1 = col1;//让中介认识具体的同事类
m->col2 = col2;//让中介认识具体的同事类
col1->Send("吃饭了吗?");
col2->Send("还没吃,你请吗?");
system("pause");
}

参考:传智播客--王保明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: