设计模式——中介者模式/调停者模式(C++实现)

设计模式——中介者模式/调停者模式(C++实现)

 #include <iostream>
#include <string> using namespace std; class Colleague; class Mediator
{
public:
virtual void Send(string strMessage, Colleague* pstColleague) = ;
}; class Colleague
{
public:
Colleague(Mediator* pstMediator): m_pstMediator(pstMediator)
{ } virtual void Send(string strMes) = ; virtual void Notify(string strMes) = ; protected:
Mediator* m_pstMediator;
}; class ConcreteColleagueA: public Colleague
{
public:
ConcreteColleagueA(Mediator* pstMediator):Colleague(pstMediator)
{ } virtual void Send(string strMsg)
{
m_pstMediator->Send(strMsg, this); } virtual void Notify(string strMes)
{
cout<< "同事1得到消息: "<< strMes<< endl;
}
}; class ConcreteColleagueB: public Colleague
{
public:
ConcreteColleagueB(Mediator* pstMediator):Colleague(pstMediator)
{ } virtual void Send(string strMsg)
{
m_pstMediator->Send(strMsg, this); } virtual void Notify(string strMes)
{
cout<< "同事2得到消息: "<< strMes<< endl;
}
}; class ConcreteMediator: public Mediator
{
public:
void SetColleagueA(ConcreteColleagueA* pstColleague)
{
m_pstColleagueA = pstColleague;
} void SetColleagueB(ConcreteColleagueB* pstColleague)
{
m_pstColleagueB = pstColleague;
} virtual void Send(string strMes, Colleague* pstColleague)
{
if (pstColleague == m_pstColleagueA)
{
m_pstColleagueB->Notify(strMes);
}
else
{
m_pstColleagueA->Notify(strMes);
}
} private:
ConcreteColleagueA* m_pstColleagueA;
ConcreteColleagueB* m_pstColleagueB;
}; int main(int argc, char* argv[])
{
ConcreteMediator* pstMediatorA = new ConcreteMediator(); ConcreteColleagueA* pstColleagueA = new ConcreteColleagueA(pstMediatorA);
ConcreteColleagueB* pstColleagueB = new ConcreteColleagueB(pstMediatorA); pstMediatorA->SetColleagueA(pstColleagueA);
pstMediatorA->SetColleagueB(pstColleagueB); pstColleagueA->Send("How are you?");
pstColleagueB->Send("I am fine, Thank You!"); return ;
}
////////////////////////////////////////////
[root@ ~/learn_code/design_pattern/21_mediator]$ ./mediator
同事2得到消息: How are you?
同事1得到消息: I am fine, Thank You!
上一篇:WEB架构师成长之路 二


下一篇:EntityFramework优缺点