设计模式复习-中介者模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式复习-中介者模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#pragma once
#include "stdafx.h"
#include<map>
#include<set>
#include<string>
#include<iostream>
using namespace std;/*設計模式-中介者模式(Mediator)用一個中介對象來封裝一系列的對象交互。中介者使各個對象不需要
顯示地相互引用,從而使其耦合松散,而且可以獨立地改變他們之間的交互。
中介者模式的有點來自集中控制,其缺點也是他,中介者模式一般應用于一組對象
定義良好但是復雜的方式進行通訊的場合,以及想定制一個分布式在多個類中的行為,
而又不想生成太多的子類的場合。
*/class CMediator {//抽象中介者
public:virtual void Send(const string &strPeople, const string &strMessage) = 0;
};class CColleague {//抽象同事類
protected:CMediator *mpMediator;
public:CColleague(CMediator *pMediator) {mpMediator = pMediator;}virtual void Notify(const string &strMessage) = 0;
};class CConcreteColleague1 :public CColleague {//同事類1
public:CConcreteColleague1(CMediator *pMediator) :CColleague(pMediator) {}void Send(const string &strPeople, const string &strMessage) {mpMediator->Send(strPeople , strMessage);}void Notify(const string &strMessage) {cout << "tong shi 1 de dao xin xi:" << strMessage << endl;}
};class CConcreteColleague2 :public CColleague {//同事類2
public:CConcreteColleague2(CMediator *pMediator) :CColleague(pMediator) {}void Send(const string &strPeople, const string &strMessage) {mpMediator->Send(strPeople, strMessage);}void Notify(const string &strMessage) {cout << "tong shi 2 de dao xin xi:" << strMessage << endl;}
};class CConcreteMediator :public CMediator {//具體中介者類
private:map<string, CColleague*>mpColleague;
public:CConcreteMediator() {mpColleague.clear();}void Send(const string &strPeople, const string &strMessage) {mpColleague[strPeople]->Notify(strMessage);}void AddColleague(const string &strPeople ,CColleague * pColleague) {mpColleague[strPeople] = pColleague;}
};int main() {CConcreteMediator *pM = new CConcreteMediator();CConcreteColleague1 *pC1 = new CConcreteColleague1(pM);CConcreteColleague2 *pC2 = new CConcreteColleague2(pM);pM->AddColleague("pC1", pC1);pM->AddColleague("pC2", pC2);pC1->Send("pC2","chi fan mei?");pC2->Send("pC1", "mei ne");delete pM, delete pC1, delete pC2;getchar();return 0;
}
?
總結
以上是生活随笔為你收集整理的设计模式复习-中介者模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式复习-职责链模式
- 下一篇: 设计模式复习-享元模式