简介

中介者模式,定义了一个封装了很多交互者的对象,中介者不需要交互者之间彼此显示的引用,并且可以独立地改变它们的交互。将对象之间N对N的关系,简化成了1对N的关系。现实中的中介者也很多,有房产中介,黄牛,媒人等。

UML类图

clipboard.png

示例

我们以房产中介为例,阐述中介者模式使用的例子。中介角色要接受卖房和买房的登记,要发布房源信息,卖房的通过中介发布房源信息。
中介者相关类,mediator.h

#ifndef MEDIATOR_H
#define MEDIATOR_H
#include <string>
#include <set>
#include <iostream>

using namespace std;
class CMediator;
class CColledge
{
public:
    CColledge(string strName):m_strName(strName){}
    virtual void ReceiveMsg(const string& strContent) = 0;
    virtual void SendMessage(CMediator* pMediator, const string& strContent) = 0;
protected:
    string m_strName;
};

class CHouser:public CColledge
{
public:
    CHouser(string strName):CColledge(strName){}
    void ReceiveMsg(const string& strContent);
    void SendMessage(CMediator* pMediator, const string& strContent);
};

class CMediator
{
public:
    virtual void Add(CColledge* pColledge) = 0;
    virtual void DistributeMessage(string strContent) = 0;
};

class CHouseMediator:public CMediator
{
public:
    void Add(CColledge* pColledge);
    void DistributeMessage(string strContent);
private:
    set<CColledge*> m_colledgeContainer;
};


#endif

中介者相关实现,mediator.cpp

#include "mediator.h"

void CHouser::ReceiveMsg(const string& strContent)
{
    cout<<m_strName<<" Received "<<strContent<<endl;
}
void CHouser::SendMessage(CMediator* pMediator, const string& strContent)
{
    pMediator->DistributeMessage(strContent);
}

void CHouseMediator::Add(CColledge* pColledge)
{
    m_colledgeContainer.insert(pColledge);
}
void CHouseMediator::DistributeMessage(string strContent)
{
    for(set<CColledge*>::iterator iter = m_colledgeContainer.begin(); iter != m_colledgeContainer.end(); ++ iter)
    {
        (*iter)->ReceiveMsg(strContent);
    }
}

调用者,main.cpp

#include "mediator.h"

#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
int main(int argc, char* argv[])
{
    CColledge* pHouser = new CHouser("John");
    CColledge* pHouseBuyerA = new CHouser("Tom");
    CColledge* pHouseBuyerB = new CHouser("Jim");

    CMediator* pMediator = new CHouseMediator();
    pMediator->Add(pHouseBuyerA);
    pMediator->Add(pHouseBuyerB);
    pHouser->SendMessage(pMediator, "Test roda,1-101, 1000w");
    SAFE_DELETE(pHouser);
    SAFE_DELETE(pHouseBuyerA);
    SAFE_DELETE(pHouseBuyerB);
    SAFE_DELETE(pMediator);
    return 0;
}

one_piece
26 声望8 粉丝

« 上一篇
迭代器模式
下一篇 »
备忘录模式