中介模式 Mediator

两个类之间通信,不通过直接通信的方式,而是中间加一层类似于中介的类,中介者模式,就类比租房时找中介那会

// Mediator.cpp : Defines the entry point for the console application.

//



#include "stdafx.h"

#include <string>

#include <VECTOR>

#include <iostream>

using namespace std;



class Colleague{            //抽象同事类

public: 

    Colleague(string name):m_name(name){}

    virtual void sendmsg(string msg) = 0;

    virtual void notifyrecvivemsg(string msg) = 0;

    string getname(){

        return m_name;

    }

    virtual ~Colleague(){}

private:

    string m_name;

};



class Mediator{             //抽象中介者类

public:

    virtual void send(string msg,Colleague * des) = 0;

    virtual void addgroup(Colleague * p) = 0;

    virtual ~Mediator(){}

};



class ConcreateMediator:public Mediator{      //具体中介者

public:

    void send(string msg,Colleague * res){

        cout<<res->getname()<<" send msg : "<<msg<<endl;

        if(res != covec[0])

            covec[0]->notifyrecvivemsg(msg);

        else

            covec[1]->notifyrecvivemsg(msg);

    }

    void addgroup(Colleague * p){

        covec.push_back(p);

    }

private:

    vector<Colleague * > covec;

};



class ConcreateColleague:public Colleague{      //具体同事

public:

    ConcreateColleague(string name,Mediator * media):Colleague(name){

        pmedia = media;

    }

    void sendmsg(string msg){

        pmedia->send(msg,this);             //通过中介者发送,然后中介者提醒接受者接收

    }

    void notifyrecvivemsg(string msg){

        cout<<this->getname()<<" recv msg : "<<msg<<endl;

    }

private:

    Mediator *pmedia;

};



int main(int argc, char* argv[])

{

    ConcreateMediator * pmedia = new ConcreateMediator();

    Colleague * worker1 = new ConcreateColleague("xiaowang",pmedia);

    Colleague * worker2 = new ConcreateColleague("xiaohong",pmedia);

    pmedia->addgroup(worker1);

    pmedia->addgroup(worker2);



    worker1->sendmsg("hello");

    worker2->sendmsg("nihaoa");

    delete worker1;

    delete worker2;

    delete pmedia;

    return 0;

}

 

你可能感兴趣的:(media)