行为设计模式---中介者模式(Mediator)

来源:互联网 发布:黑客军团 知乎 编辑:程序博客网 时间:2024/06/04 18:24

 中介者模式:定义一个对象封装一系列多个对象如何相互作用,使得对象间不需要显式地相互引用,
从而使其耦合更加松散,并且还让我们可以独立变化多个对象相互作用。如QQ聊天室

#include <iostream>
#include <map>
#include <string>
#include <string.h>
using namespace std;

class Colleague;
class IMediator
{
public:
        virtual ~IMediator() {}
        virtual void add(Colleague *) = 0;
        virtual void notify(const char *from, const char *to, const char *msg) = 0;
};

class Colleague
{
public:
        Colleague(const char *name)
        {
                strcpy(name_, name);
        }
        virtual ~Colleague()
        {}
        char *getName()
        {
                return name_;
        }
        void setMediator(IMediator *mediator)
        {
                mediator_ = mediator;
        }
        void send(const char *to, const char *msg)
        {
                mediator_->notify(name_, to, msg);
        }
        void receive(const char *from, const char *msg)
        {
                cout << from << " to " << name_ << " : " << msg << endl;
        }

private:
        IMediator *mediator_;
        char name_[32];
};

class Mediator : public IMediator
{
public:
        ~Mediator()
        {}
        void add(Colleague *colleague)
        {
                pool[colleague->getName()] = colleague;
                colleague->setMediator(this);
        }

        void notify(const char *from, const char *to, const char *msg)
        {
                Colleague *colleague = pool[to];
                colleague->receive(from, msg);
        }

private:
        map<string, Colleague *> pool;
};

int main()
{
        Colleague Collin("Collin");
        Colleague Lola("Lola");
        Mediator mediator;

        mediator.add(&Collin);
        mediator.add(&Lola);

        Collin.send("Lola", "Hello, Lola");
        Lola.send("Collin", "Hi, this is Lola");

        return 0;
}

 


 

0 0
原创粉丝点击