现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式20:中介者模式【行为型】

2013-03-09 12:22 工业·编程 ⁄ 共 1601字 ⁄ 字号 暂无评论

#include <iostream>
using namespace std;

//
struct IMeditor;

struct IPerson
{
public:
    IPerson() : m_pMeditor(NULL) { }
    virtual ~IPerson() { }

    void SetMeditor(IMeditor *pMeditor) { m_pMeditor = pMeditor; }
    virtual void SendMessage(string message) = 0;
    virtual void RecvMessage(string message) = 0;

protected:
    IMeditor *m_pMeditor;
};

struct IMeditor
{
public:
    IMeditor(IPerson *pRenter, IPerson *pLandlord) : m_pRenter(pRenter), m_pLandlord(pLandlord) { }
    virtual ~IMeditor() { }

    virtual void SendMessage(string message, IPerson *pPerson) = 0;

protected:
    IPerson *m_pRenter, *m_pLandlord;
};

class CRenter : public IPerson
{
public:
    CRenter() { }
    virtual ~CRenter() { }

    virtual void SendMessage(string message) { m_pMeditor->SendMessage(message,this); }
    virtual void RecvMessage(string message) { cout<<"租房者收到信息:"<<message.c_str()<<endl; }
};

class CLandlord : public IPerson
{
public:
    CLandlord() { }
    virtual ~CLandlord() { }

    virtual void SendMessage(string message) { m_pMeditor->SendMessage(message,this); }
    virtual void RecvMessage(string message) { cout<<"房东收到信息:"<<message.c_str()<<endl; }
};

class CHouseMeditor : public IMeditor
{
public:
    CHouseMeditor(IPerson *pRenter, IPerson *pLandlord) : IMeditor(pRenter,pLandlord) { }
    virtual ~CHouseMeditor() { }

    virtual void SendMessage(string message, IPerson *pPerson)
    {
        if(m_pRenter == pPerson)
            m_pLandlord->RecvMessage(message);
        else
            m_pRenter->RecvMessage(message);
    }
};

//
void main()
{
    CRenter renter;
    CLandlord landlord;

    CHouseMeditor houseMeditor(&renter,&landlord);

    renter.SetMeditor(&houseMeditor);
    landlord.SetMeditor(&houseMeditor);

    renter.SendMessage("求租房子。");
    landlord.SendMessage("出售房子。");
}

给我留言

留言无头像?