设计模式—中介者模式(二十一)

        软件领域中的设计模式的重要性不言而喻。设计模式中运用了面向对象编程语言的重要特性:封装、继承、多态。虽然知道这些特性的定义但是并没有做到真正的理解,这样特性有什么作用?用于什么场合中等等问题,带着疑问开始学习设计模式,主要参考《大话设计模式》和《设计模式:可复用面向对象软件的基础》两本书。

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


        抽象中介者:定义好同事类对象到中介者对象的接口,用于各个同事类之间的通信。一般包括一个或几个抽象的事件方法,并由子类去实现。

        中介者实现类:从抽象中介者继承而来,实现抽象中介者中定义的事件方法。从一个同事类接收消息,然后通过消息影响其他同时类。

        同事类:如果一个对象会影响其他的对象,同时也会被其他对象影响,那么这两个对象称为同事类。同事类越多,关系越复杂。并且,同事类也可以表现为继承了同一个抽象类的一组实现组成。在中介者模式中,同事类之间必须通过中介者才能进行消息传递。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Colleague;
//中介者类
class Mediator
{
public:
	virtual void Send(string message, Colleague* colleague) = 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)
			col2->Notify(message);
		else
			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("必须去啊,你教教我!!!");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章