中介者模式

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

以租房为例子,如果没有房屋中介,那么房客要自己找房东,而房东也要自己找房客,非常不方便。有了房屋中介机构就方便了,房东可以把要出租的房屋信息放到中介机构,而房客可以去中介机构咨询。在软件中,就是多个对象之间需要通信,如果没有中介,对象就需要知道其他对象,最坏情况下,可能需要知道所有其他对象,而有了中介对象就方便多了,对象只需与中介对象通信,而不用知道其他的对象。这就是中介者模式

 

#include <iostream>
#include <string>


class IMediator;

class IPerson
{
public:
    IPerson() {}
    virtual ~IPerson() {}
    
    virtual void setMediator(IMediator * mediator) = 0;
    virtual void sendMsg(const std::string &msg) = 0;
    virtual void getMsg(const std::string &msg) = 0;

protected:
    IMediator *m_mediator;
};

class IMediator
{
public:
    IMediator() = default;
    virtual ~IMediator() = default;
    
    virtual void sendMsg(const std::string &msg, IPerson *p) = 0;
    virtual void setA(IPerson *A) = 0;
    virtual void setB(IPerson *B) = 0;
};

class CHouseMediator : public IMediator
{
public:
    CHouseMediator() : m_A(nullptr), m_B(nullptr) {}
    ~CHouseMediator() = default;
    
    void setA(IPerson *A) override
    {
        m_A = A;
    }

    void setB(IPerson *B) override
    {
        m_B = B;
    }

    void sendMsg(const std::string &msg, IPerson *p) override
    {
        if (p == m_A)
            m_B->getMsg(msg);
        else
            m_A->getMsg(msg);
    }

private:
    IPerson *m_A;
    IPerson *m_B;
};

class CCustomer : public IPerson
{
public:
    CCustomer() {}
    ~CCustomer() {}
    
    void setMediator(IMediator * mediator) override
    {
        m_mediator = mediator;
    }

    void sendMsg(const std::string &msg) override
    {
        m_mediator->sendMsg(msg, this);
    }

    void getMsg(const std::string &msg) override
    {
        std::cout << "买方收到信息: " << msg << '\n';
    }
};

class CLandlord : public IPerson
{
public:
    CLandlord() {}
    ~CLandlord() {}
    
    void setMediator(IMediator * mediator) override
    {
        m_mediator = mediator;
    }

    void sendMsg(const std::string &msg) override
    {
        m_mediator->sendMsg(msg, this);
    }

    void getMsg(const std::string &msg) override
    {
        std::cout << "卖方收到信息: " << msg << '\n';
    }
};


int main()
{
    IMediator *mediator = new CHouseMediator();
    IPerson *p1 = new CCustomer();
    IPerson *p2 = new CLandlord();

    mediator->setA(p1);
    mediator->setB(p2);
    p1->setMediator(mediator);
    p2->setMediator(mediator);

    p1->sendMsg("买一套上海的200平大房子");
    p2->sendMsg("出售一套上海200平大房子");

    delete mediator;
    delete p1;
    delete p2;

    return 0;
}

 

posted @ 2019-03-04 15:11  二狗啸地  阅读(146)  评论(0编辑  收藏  举报