mediator模式

作者: 老练子丶2017 | 来源:发表于2017-11-24 16:04 被阅读0次

    将对象封装在类似中介的类中,对象之间的通信他们本身不用关心

    mediator.h

    #ifndef _MEDIATOR_H

    #define _MEDIATOR_H

    #include <iostream>

    #include <string>

    using namespace std;

    class Mediator

    {

    public:

    Mediator() {

    }

    ~Mediator() {

    }

    virtual void DoActionFromAtoB()=0;

    virtual void DoActionFromBtoA()=0;

    };

    class Colleage

    {

    public:

    virtual ~Colleage() {

    }

    virtual void Action()=0;

    Colleage() {

    }

    Colleage(Mediator* mdt) : _mdt(mdt) {

    }

    public:

    Mediator* _mdt;

    string _sdt;

    };

    class ConcreteColleageA : public Colleage

    {

    public:

    ConcreteColleageA() {

    }

    ConcreteColleageA(Mediator* mdt) : Colleage(mdt) {

    }

    ~ConcreteColleageA() {

    }

    void Action() {

    _mdt->DoActionFromAtoB();

    cout << "state of concreteColleageA:" << _sdt << endl;

    }

    public:

    string _sdt;

    };

    class ConcreteColleageB : public Colleage

    {

    public:

    ConcreteColleageB() {

    }

    ConcreteColleageB(Mediator* mdt) : Colleage(mdt) {

    }

    ~ConcreteColleageB() {

    }

    void Action() {

    _mdt->DoActionFromBtoA();

    cout << "state of concreteColleageB:" << _sdt << endl;

    }

    public:

    string _sdt;

    };

    class ConcreteMediator : public Mediator

    {

    public:

    ConcreteMediator() {

    }

    ~ConcreteMediator() {

    }

    ConcreteMediator(Colleage* clgA, Colleage* clgB) : _clgA(clgA), _clgB(clgB) {

    }

    void DoActionFromAtoB() {

    _clgB->_sdt = _clgA->_sdt;

    }

    void DoActionFromBtoA() {

    _clgA->_sdt = _clgB->_sdt;

    }

    void IntroColleage(Colleage* clgA, Colleage* clgB) {

    _clgA = clgA;

    _clgB = clgB;

    }

    public:

    Colleage* _clgA;

    Colleage* _clgB;

    };

    #endif // _MEDIATOR_H

    mediator.cpp

    #include "mediator.h"

    int main()

    {

    ConcreteMediator* m = new ConcreteMediator;

    ConcreteColleageA* c1 = new ConcreteColleageA(m);

    ConcreteColleageB* c2 = new ConcreteColleageB(m);

    m->IntroColleage(c1, c2);

    c1->_sdt = "old";

    c2->_sdt = "old";

    c1->Action();

    c2->Action();

    c1->_sdt = "new";

    c1->Action();

    c2->Action();

    c2->_sdt = "old";

    c2->Action();

    c1->Action();

    return 0;

    }

    编译: make mediator

    相关文章

      网友评论

        本文标题:mediator模式

        本文链接:https://www.haomeiwen.com/subject/byrfbxtx.html