中介者模式C++

2018-05-10  本文已影响0人  涵仔睡觉

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

中介者模式结构图

image

中介者模式基本代码

#include <iostream>
#include <string>
using namespace std;

class Colleague;

class Mediator {
public:
    virtual void Send(string message, Colleague* colleague) = 0;
    virtual ~Mediator() {}
};

class Colleague {
protected:
    Mediator* mediator;
public:
    Colleague(Mediator* m) { mediator = m; }
};

class ConcreteColleague1 : public Colleague {
public:
    ConcreteColleague1(Mediator* m) : Colleague(m) {}
    void Send(string message) {
        mediator->Send(message, this);
    }
    void Notify(string message) {
        cout << "ConcreteColleague1 received: " << message << endl;
    }
};

class ConcreteColleague2 : public Colleague {
public:
    ConcreteColleague2(Mediator* m) : Colleague(m) {}
    void Send(string message) {
        mediator->Send(message, this);
    }
    void Notify(string message) {
        cout << "ConcreteColleague2 received: " << message << endl;
    }
};

class ConcreteMediator : public Mediator {
private:
    ConcreteColleague1* c1;
    ConcreteColleague2* c2;
public:
    void set(ConcreteColleague1* c) { c1 = c; }
    void set(ConcreteColleague2* c) { c2 = c; }
    void Send(string message, Colleague* colleague) {
        if (colleague == c1) c2->Notify(message);
        else c1->Notify(message);
    }
};

int main() {
    ConcreteMediator* m = new ConcreteMediator();
    ConcreteColleague1* c1 = new ConcreteColleague1(m);
    ConcreteColleague2* c2 = new ConcreteColleague2(m);

    m->set(c1);
    m->set(c2);

    c1->Send("Hello");   // ConcreteColleague2 received: Hello
    c2->Send("World");  // ConcreteColleague1 received: World

    delete m;
    delete c1;
    delete c2;
    return 0;
}

应用场景

中介者模式一般用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。

优点:

缺点:

上一篇下一篇

猜你喜欢

热点阅读