首页 > 代码库 > 中介者模式

中介者模式

中介者模式,用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。

ConcreteMediator是具体中介者对象,实现抽象类的方法,它需要知道所有具体同事类,并从具体同事接受消息,向具体同事对象发出命令。

中介者模式的优缺点:
中介者的出现减少了各个对象之间的耦合性,使得可以独立的改变和复用。它使得各个对象之间的交互转移到中介者上,从一个全局观上简化了对象之间的联系方式。
但是缺点也是明显的,由于中介者进行集中化控制,使得中介者异常复杂,增加对象都需要修改中介者,所以这个类一般用于对象联系比较复杂,但是对象定义良好的时候

代码:
//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;
}