设计模式-行为模式-中介者模式

2020-04-29  本文已影响0人  阿棍儿_Leon

中介者模式可以对多个对象之间的交互进行解耦。这个模式种有2类角色,一个是中介者,另一类是需要互相交互的对象。

以下代码定义了中介者。

#include <iostream>
#include <vector>

using namespace std;

class Mediator
{
public:
    virtual ~Mediator(){}
    virtual void Request() = 0;
    virtual void Register(class Colleague* colleague) = 0;
    virtual void UnRegister(class Colleague* colleague) = 0;
};

class ConcreteMediator:public Mediator
{
private:
    vector<class Colleague*> m_pColleagues;
public:
    void Request();
    void Register(class Colleague* colleague);
    void UnRegister(class Colleague* colleague);
};

以下代码定义了交互对象。

class Colleague
{
protected:
    Mediator* m_pMediator;
public:
    Colleague(Mediator* mediator):m_pMediator(mediator)
    {
        m_pMediator->Register(this);
    }
    virtual void Request() = 0;
    virtual void Notify() = 0;
    virtual ~Colleague()
    {
        m_pMediator->UnRegister(this);
    }
};

class ConcreteColleague0:public Colleague
{
public:
    ConcreteColleague0(Mediator* mediator):Colleague(mediator){}
    void Request()
    {
        cout<<endl<<__PRETTY_FUNCTION__<<endl;
        m_pMediator->Request();
    }
    void Notify()
    {
        cout<<__PRETTY_FUNCTION__<<endl;
    }
};

class ConcreteColleague1:public Colleague
{
public:
    ConcreteColleague1(Mediator* mediator):Colleague(mediator){}
    void Request()
    {
        cout<<endl<<__PRETTY_FUNCTION__<<endl;
        m_pMediator->Request();
    }
    void Notify()
    {
        cout<<__PRETTY_FUNCTION__<<endl;
    }
};

以下代码是中介者的方法实现。

void ConcreteMediator::Request()
{
    for (auto it : m_pColleagues)
    {
        it->Notify();
    }
}
void ConcreteMediator::Register(Colleague* colleague)
{
    m_pColleagues.push_back(colleague);
}
void ConcreteMediator::UnRegister(Colleague* colleague)
{
    for (vector<Colleague*>::iterator it; it != m_pColleagues.end(); ++it)
    {
        if (*it == colleague)
        {
            m_pColleagues.erase(it);
        }
    }
}

以下代码演示了中介者交互过程,这里的实现类似于聊天室,一个对象发送,所有对象都收到消息。

int main(void){

    Mediator* mediator = new ConcreteMediator();
    Colleague* C0 = new ConcreteColleague0(mediator);
    Colleague* C1 = new ConcreteColleague1(mediator);
    C0->Request();
    C1->Request();
    return 0;
}

输出


virtual void ConcreteColleague0::Request()
virtual void ConcreteColleague0::Notify()
virtual void ConcreteColleague1::Notify()

virtual void ConcreteColleague1::Request()
virtual void ConcreteColleague0::Notify()
virtual void ConcreteColleague1::Notify()
上一篇下一篇

猜你喜欢

热点阅读