基本代码

#include <iostream>
#include<vector>
#include<string>
#include<ctime>

using namespace std;

class Colleague;

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

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

class ConcreteColleague1 :public Colleague
{
public:
    ConcreteColleague1(Mediator* mediator)
        :Colleague(mediator)
    { }

    void Send(string message)
    {
        mediator->Send(message, this);
    }

    void Notify(string message)
    {
        cout << "同事1得到消息:" << message << endl;
    }
};

class ConcreteColleague2 :public Colleague
{
public:
    ConcreteColleague2(Mediator* mediator)
        :Colleague(mediator)
    { }

    void Send(string message)
    {
        mediator->Send(message, this);
    }

    void Notify(string message)
    {
        cout << "同事2得到消息:" << message << endl;
    }
};

class ConcreteMediator :public Mediator
{
private:
    ConcreteColleague1* colleague1;
    ConcreteColleague2* colleague2;

public:
    void setConcreteColleague1(ConcreteColleague1* colleague1_t) { colleague1 = colleague1_t; }
    void setConcreteColleague2(ConcreteColleague2* colleague2_t) { colleague2 = colleague2_t; }
    void Send(string message, Colleague* colleague)
    {
        if (colleague == colleague1)
            colleague2->Notify(message);
        else
            colleague1->Notify(message);
    }
};



int main()
{
    ConcreteMediator* m = new ConcreteMediator();

    ConcreteColleague1* c1 = new ConcreteColleague1(m);
    ConcreteColleague2* c2 = new ConcreteColleague2(m);

    m->setConcreteColleague1(c1);
    m->setConcreteColleague2(c2);

    c1->Send("吃过饭了么?");
    c2->Send("没有,你打算请客么?");


    system("pause");
    return 0;
}

中介模式的优缺点

12-16 09:53