概述:
假設我們開發一個圖片處理軟件,裏面肯定包括很多相關功能,比如說剪切,旋轉,濾鏡,美化等等,而我們這些功能所要處理的對象是固定的,就是我們所顯示的那張圖片。但是我們不能把所有的功能羅列到一個tab上,雖然這樣處理方便但是不美觀。這是我們可以這樣子:用一箇中介者類負責所有功能的初始化和具體執行,我們需要功能時直接調用中介者類即可。
中介者模式就是定義一箇中介對象來封裝系列對象之間的交互。中介者使各個對象不需要顯示地相互引用,從而使其耦合性鬆散,而且可以獨立地改變他們之間的交互。
類圖和實例
Mediator類:抽象中介者,定義了同事對象交互的接口。
ConcreteMediator類:具體中介者對象,實現抽象類中的方法,此具體中介者對象需要知道所有具體同事類,並從具體同事接受消息,向具體同事對象發送命令。
Colleague類:抽象同事類。
ConcreteColleague類:具體同事類,實現抽象同事類中的方法。每一個同時類需要知道中介者對象;每個具體同事類只需要瞭解自己的行爲,而不需要了解其他同事類的情況。
- #include <iostream>
- #include <vector>
- #include <string>
- 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;
- }
適用性:
1.一組對象以定義良好但是複雜的方式進行通信。產生的相互依賴關係結構混亂且難以理解。
2.一個對象引用其他很多對象並且直接與這些對象通信,導致難以複用該對象。
3.想定製一個分佈在多個類中的行爲,而又不想生成太多的子類。
優缺點:
使用中介者模式的優點:
1.降低了系統對象之間的耦合性,使得對象易於獨立的被複用。
2.提高系統的靈活性,使得系統易於擴展和維護。
使用中介者模式的缺點:
由於我們這個“中介“承擔了較多的責任,所以一旦這個中介對象出現了問題,那麼整個系統就會受到重大的影響。