Mediator模式

来源:互联网 发布:知乐作品全集百度云 编辑:程序博客网 时间:2024/06/05 23:55

Mediator模式

一、意图

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

 

二、适用性

1.一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解。

2.一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。

3.想定制一个分布在多个类中的行为,而又不想生成太多的子类。

 

三、结构

 



四、代码

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

#include <vector>

#include <math.h>

#include <qxmlstream.h>

#include <QDebug>

#include <windows.h>

#include <unistd.h>

#include <QApplication>

 

//1

class CColleague;

 

class CMediator

{

public:

    CMediator()

    {

        m_vColleague.clear();

    }

    ~CMediator()

    {

        m_vColleague.clear();

    }

    virtual void Register(CColleague* col)

    {

        m_vColleague.push_back(col);

    }

    virtual void Operation(CColleague* from, CColleague* toName, QString msg){}

 

protected:

    std::vector<CColleague*> m_vColleague;

};

 

//2

class CColleague

{

public:

    CColleague(CMediator* mediator)

    {

        m_pCMediator = mediator;

        mediator->Register(this);

    }

    ~CColleague(){}

 

    virtual void send(CColleague* toName, QString msg){}

 

    virtual QString getName()

    {

        return m_name;

    }

//private:

    virtual void notify(CColleague* fromName, QString msg){}

 

protected:

    CMediator* m_pCMediator;

    QString m_name;

};

 

//3

class CConcreteMediator : public CMediator

{

public:

    virtual void Operation(CColleague* from, CColleague* toName, QString msg)

    {

        for(int i = 0; i < m_vColleague.size(); i++)

        {

             if(toName->getName() == m_vColleague[i]->getName())

             {

                 m_vColleague[i]->notify(from, msg);

             }

        }

    }

};

 

//4

class CConcreteColleague : public CColleague

{

public:

    CConcreteColleague(CMediator* mediator, QString name) : CColleague(mediator)

    {

        m_name = name;

    }

 

    virtual void send(CColleague* toName, QString msg)

    {

        qDebug() << m_name << " send to " << toName->getName() << msg;

        this->m_pCMediator->Operation(this, toName, msg);

    }

 

//private:

    virtual void notify(CColleague* fromName, QString msg)

    {

        qDebug() << getName() << "recv Msg from" << fromName->getName() << msg;

    }

};

 

int main(int argc, char** argv)

{

    QApplication app(argc, argv);

 

    CConcreteMediator* mediator = new CConcreteMediator();

 

    CConcreteColleague* colleagueOne = new CConcreteColleague(mediator, "ColleagueOne");

    CConcreteColleague* colleagueTwo = new CConcreteColleague(mediator, "ColleagueTwo");

    CConcreteColleague* colleagueThree = new CConcreteColleague(mediator, "ColleagueThree");

 

    colleagueOne->send(colleagueTwo, "hello, no. two");

    colleagueThree->send(colleagueOne, "hello");

 

    return app.exec();

}

 

 

 

 

 

 

原创粉丝点击