Mediator mode (Mediator)

Mediator pattern (Mediator): A mediator object is used to encapsulate a series of object interactions. The mediator makes the objects do not need to refer to each other explicitly, so that the coupling is loose, and the interaction between them can be changed independently. The

mediator Patterns are generally used where a set of objects communicate in a well-defined but complex way, and where you want to customize the behavior of a class that is distributed across multiple classes, without creating too many subclasses




#include <iostream>
using namespace std;

class Mediator
{
public:
    void execute(int type)
    {
        if(type==1){
            cout << "do thing 1" << endl;
        }else if(type==2){
            cout << "do thing 2" << endl;
        }
    }
};

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

class Colleague1:public Colleague
{
public:
    Colleague1(Mediator* mediator):Colleague(mediator){

    }
    void operation1(){
        mMediator->execute(1);
    }
};

class Colleague2:public Colleague
{
public:
    Colleague2(Mediator* mediator):Colleague(mediator){

    }
    void operation2(){
        mMediator->execute(2);
    }
};

intmain()
{
    Mediator* mediator = new Mediator;
    Colleague1* colleague1 = new Colleague1(mediator);
    Colleague2* colleague2 = new Colleague2(mediator);
    colleague1->operation1();
    colleague2->operation2();
}



do thing 1
do thing 2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326507934&siteId=291194637