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

C++设计模式[十六]中介者模式

2015-11-23 16:01 561 查看
这个模式正如名字所言就是一个中介者,不管两者有什么方法属性,通过中介然后建立一种关系并实现。



Mediator:中介者,它定义了一个接口用于与各个Colleague对象通信;

ConcreteMediator:具体的中介者,它通过协调各Colleague对象实现协作行为;并了解和维护它的各个Colleague;

Colleague:同事类,每一个同事类都知道它的中介者对象;每一个同时对象在需要与其他的同事通信的时候,而是与它的中介者通信。

它们之间是按照以下方式进行协作的:

同事向一个中介者对象发送和接收请求。中介者在各同事间适当地转发请求以实现协作行为。

在下列情况下使用中介者模式:

一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解;
一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象;
想定制一个分布在多个类中的行为,而又不想生成太多的子类。

#include"stdafx.h"
#include<string>
#include <iostream>
#include <vector>
using namespace std;
class Colleage
{
private:
	string name;
	string content;
public:
	Colleage(string n = " ") :name(n){};
	void set_name(string name)
	{
		this->name = name;
	}
	string get_name()
	{
		return this->name;
	}
	void set_content(string content)
	{
		this->content = content;
	}
	string get_content()
	{
		if (content.size() != 0)
			return content;
		else return "Copy that";
	}
	virtual void talk(){};

};

class Monitor : public Colleage
{
public:
	Monitor(string n = "") :Colleage(n){};
	virtual void talk()
	{
		cout << "班长 " << get_name() << " 说:" << get_content() << endl;
	}
};

class Secretary : public Colleage
{
public:
	Secretary(string n = "") :Colleage(n){};
	virtual void talk()
	{
		cout << "团支书 " << get_name() << " 说:" << get_content() << endl;
	}
};

class StudentA : public Colleage
{
public:
	StudentA(string n = "") :Colleage(n){};
	virtual void talk()
	{
		cout << "学生 A " << get_name() << " 说:" << get_content() << endl;
	}
};

class StudentB : public Colleage
{
public:
	StudentB(string n = "") :Colleage(n){};
	virtual void talk()
	{
		cout << "学生 B " << get_name() << " 说:" << get_content() << endl;
	}
};

class Mediator
{
public:
	vector<Colleage*> studentList;
	virtual void add_student(Colleage *student)
	{
		studentList.push_back(student);
	};
	virtual void notify(Colleage *student){};
};

class QQMediator : public Mediator
{
public:
	virtual void notify(Colleage *student)
	{
		student->talk();
		for (int i = 0; i < studentList.size(); ++i)
		{
			if (student != studentList[i])
			{
				studentList[i]->talk();
			}
		}
	};
};
int main()
{
	QQMediator qq;
	Monitor *studentMonitor = new Monitor("Foxx");
	Secretary *studentSecretary = new Secretary("TC");
	StudentA *studentA = new StudentA("Jack");
	StudentB *studentB = new StudentB("Frank");
	qq.add_student(studentSecretary);
	qq.add_student(studentA);
	qq.add_student(studentB);
	studentMonitor->set_content("明天开始放假!");
	qq.notify(studentMonitor);
	return 0;
}



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