中介者模式的c++代码实现

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

// mediator.cpp : 定义控制台应用程序的入口点。
//

#include<iostream>
using namespace std;
#include<string>
#include<list>
class Mediator;
class Colleague
{
public:
	Colleague(Mediator *m,string name)
	{
		this->m = m;
		this->name = name;
	}
	Mediator *m;
	virtual void notify(string &s,Colleague*c)
	{
		cout << this->name << " receive a message from " << c->name << " : " << s << endl;
	}
	virtual void say(string s);
	string name;
};


class ColleagueA :public Colleague
{
public:
	ColleagueA(Mediator *m,string name):Colleague(m,name)
	{
	
	}

};
class ColleagueB :public Colleague
{
public:
	ColleagueB(Mediator *m,string name):Colleague(m,name)
	{
	
	}

};
class Mediator
{
public:
	Colleague *c1;
	Colleague *c2;
	void say(string s,Colleague*from)
	{
		if(c1 == from)
		{
			c2->notify(s,c1);
		}
		else if(c2 == from)
		{
			c1->notify(s,c2);
		}
	}
	void introduceA(Colleague*c)
	{
		c1 = c;
	}
	void introduceB(Colleague*c)
	{
		c2 = c;
	}
	
};
void Colleague::say(string s)
{
	this->m->say(s,this);
}


int main(int argc, char* argv[])
{
	Mediator m;
	ColleagueA a(&m,"A");
	ColleagueB b(&m,"B");
	m.c1 = &a;
	m.c2 = &b;
	a.say("how are you?");
	b.say("i'm fine,thank you.and you?");
	a.say("i'm fine too.");
	return 0;
}


代码里简单的用两个对象交互

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值