标签:c++ 设计模式
中介者模式,用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。//Mediator.h #include "stdafx.h" #include <iostream> #include <string> using namespace std; class Colleague ; class Mediator { public : ~Mediator(){} virtual void SendMessage( string message, Colleague* pColleague) = 0; }; class Colleague { protected : Mediator* m_pMediator; public : Colleague( Mediator* pMediator) { m_pMediator = pMediator; } }; class ConcreteColleague1 :public Colleague { public : ConcreteColleague1( Mediator* pMediator) : Colleague( pMediator) {} void SendMessage( string message) { m_pMediator->SendMessage( message, this); } void GetMes( string message) { cout << "ConcreteColleague1接收到信息:" << message << endl; } }; class ConcreteColleague2 :public Colleague { public : ConcreteColleague2( Mediator* pMediator) : Colleague( pMediator) {} void SendMessage( string message) { m_pMediator->SendMessage( message, this); } void GetMes( string message) { cout << "ConcreteColleague2接收到信息:" << message << endl; } }; class ConcreteMediator :public Mediator { private : ConcreteColleague1 * m_pColleague1; ConcreteColleague2 * m_pColleague2; public : void SetColleague1( ConcreteColleague1 * colleague1 ) { m_pColleague1 = colleague1 ; } void SetColleague2( ConcreteColleague2 * colleague2 ) { m_pColleague2 = colleague2 ; } virtual void SendMessage( string message, Colleague* pColleague ) { if ( pColleague == m_pColleague1) { m_pColleague2->GetMes( message); } else { m_pColleague1->GetMes( message); } } };
// MediatorPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Mediator.h" int _tmain (int argc , _TCHAR * argv []) { ConcreteMediator * pMediator = new ConcreteMediator (); ConcreteColleague1 * pColleague1 = new ConcreteColleague1 (pMediator); ConcreteColleague2 * pColleague2 = new ConcreteColleague2 (pMediator); pMediator->SetColleague1(pColleague1); pMediator->SetColleague2(pColleague2); pColleague1->SendMessage( "吃了吗?" ); pColleague2->SendMessage( "没呢,你请客吧!" ); getchar(); return 0; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/27378461