C++ 设计模式之中介者模式
来源:互联网 发布:mac上好玩的单机游戏 编辑:程序博客网 时间:2024/05/18 19:36
Mediator中介者模式
作用:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
类图:
下面是代码实例:
#include"stdafx.h"#include<iostream>#include<string>using namespace std;//class Mediator;class Colleage;class Mediator{public:virtual ~Mediator(){}virtual void SendMsg(string,Colleage *) {}protected:Mediator(){}};class Colleage{public:virtual ~Colleage(){}/*virtual void SetMediator(Mediator *pMediator){m_Mediator = pMediator;}*/virtual void SendMsg(string msg) = 0;virtual void GetMsg(string msg) = 0;protected:Colleage(Mediator *pMediator){m_Mediator = pMediator;}Mediator * m_Mediator;private:};class ConcreteColleageA : public Colleage{public:~ConcreteColleageA(){}ConcreteColleageA(Mediator *pMediator):Colleage(pMediator) {// Colleage(pMediator); } void SendMsg(string msg) {this->m_Mediator->SendMsg(msg,this); } void GetMsg(string msg) { cout<<"ConcreteColleageA Receive:" <<msg<<endl; }};class ConcreteColleageB : public Colleage{public:~ConcreteColleageB(){} ConcreteColleageB(Mediator *pMediator): Colleage(pMediator) { //Colleage(pMediator); } void SendMsg(string msg) { this->m_Mediator->SendMsg(msg,this); } void GetMsg(string msg) { cout<<"ConcreteColleageB Receive:" <<msg<<endl; }};class ConcreteMediator : public Mediator{public:ConcreteMediator(){}~ConcreteMediator(){}void SetColleageA(Colleage *pColleage){m_ColleageA = pColleage;}void SetColleageB(Colleage *pColleage){m_ColleageB = pColleage;}void SendMsg(string msg,Colleage *pColleage){if(pColleage == m_ColleageA){m_ColleageA->GetMsg(msg);}else if(pColleage == m_ColleageB){m_ColleageB->GetMsg(msg);}}private:Colleage *m_ColleageA;Colleage *m_ColleageB;};
// MediatorMode.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include"Mediator.hpp"int _tmain(int argc, _TCHAR* argv[]){ConcreteMediator *pMediator = new ConcreteMediator(); Colleage *p1 = new ConcreteColleageA(pMediator);Colleage *p2 = new ConcreteColleageB(pMediator); pMediator->SetColleageA(p1);pMediator->SetColleageB(p2);/*pMediator->SendMsg("CCC",p1);pMediator->SendMsg("DDD",p2);*/p1->SendMsg("AAA");p2->SendMsg("BBB");system("pause");return 0;}
0 0
- 设计模式之中介者
- 设计模式 之 中介者
- 设计模式之中介者
- 设计模式之Mediator中介者模式
- 设计模式之中介者模式
- 设计模式之中介者模式
- 八 设计模式之中介者模式
- 设计模式之--中介者模式
- 设计模式之中介者模式
- c++设计模式之中介者模式
- 设计模式之-中介者模式
- 设计模式之中介者模式
- c++设计模式之中介者模式
- 设计模式之中介者模式(Mediator)
- 设计模式之中介者模式
- 设计模式之中介者模式
- JAVA-设计模式之中介者模式
- 大话设计模式之中介者模式
- Druid连接池自定义数据库密码加解密的实现
- Java的native方法是什么
- Linux系统移植实验---SD卡驱动移植
- ArcGIS 10.3 属性表乱码问题
- :target 伪类使用技巧
- C++ 设计模式之中介者模式
- 静态加载界面文件和动态加载
- 献给写作者的 Markdown 新手指南
- AlertDialog通过反射机制阻止Dialog关闭
- Log4j的使用及原理
- POJ 3264 Balanced Lineup
- 日本語:日常会话4-レストランについて
- SSM整合tomcat服务器启动不了,控制台log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more
- Swift 3实现简单条形码功能