zoukankan      html  css  js  c++  java
  • 中介模式 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;
    }
  • 相关阅读:
    sqlserver2005存储汉字成问号解决办法:
    .net c# 日期格式和常用处理
    文件夹无法访问拒绝访问,无法删除文件的,快速有效解决方法
    打印出所有的 info.plist 中的 keys、values
    利用时间戳来准确计算某个时间点具现在的时间差
    项目中的技巧经验汇总
    "Base SDK Missing"问题的解决
    UIPopoverController的使用
    给ios自带控件添加圆角边的方法
    实现程序内截屏功能的代码
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4649428.html
Copyright © 2011-2022 走看看