設計模式—中介者模式(二十一)

        軟件領域中的設計模式的重要性不言而喻。設計模式中運用了面向對象編程語言的重要特性:封裝、繼承、多態。雖然知道這些特性的定義但是並沒有做到真正的理解,這樣特性有什麼作用?用於什麼場合中等等問題,帶着疑問開始學習設計模式,主要參考《大話設計模式》和《設計模式:可複用面向對象軟件的基礎》兩本書。

        中介者模式:用一箇中介對象來封裝一系列的對象交互,中介者使各對象不需要顯示的相互引用,從而降低耦合;而且可以獨立地改變它們之間的交互。


        抽象中介者:定義好同事類對象到中介者對象的接口,用於各個同事類之間的通信。一般包括一個或幾個抽象的事件方法,並由子類去實現。

        中介者實現類:從抽象中介者繼承而來,實現抽象中介者中定義的事件方法。從一個同事類接收消息,然後通過消息影響其他同時類。

        同事類:如果一個對象會影響其他的對象,同時也會被其他對象影響,那麼這兩個對象稱爲同事類。同事類越多,關係越複雜。並且,同事類也可以表現爲繼承了同一個抽象類的一組實現組成。在中介者模式中,同事類之間必須通過中介者才能進行消息傳遞。

#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;
}


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