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