• c++ 中介者模式(mediator)


    中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。中介者模式的例子很多,大到联合国安理会,小到房屋中介。下面以房屋中介来介绍中介者模式。

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Mediator;
    
    class Person
    {
    public:
        virtual void setMediator(Mediator* mediator){};
        virtual void sendMessage(string msg) = 0;
        virtual void getMessage(){};
    protected:
        Mediator *m_mediator;
    };
    
    class Mediator 
    {
    public:
        virtual void setHost(Person* p) = 0;
        virtual void setClient(Person* p) = 0;
        virtual void sendMsg(Person* p,string msg)
        {
        
        }
    
    }; 
    
    class HouseMediator:public Mediator
    {
    public:
        void setHost(Person* p)
        {
            m_host = p;
        }
        void setClient(Person* p)
        {
            m_client = p;
        }
        void sendMsg(Person* p,string msg)
        {
            if(p == m_host)
            {
                m_client->getMessage();
            }
            else
            {
                m_host->getMessage();
            }
        }
    private:
        Person* m_host;
        Person* m_client;
    };
    
    class HostPerson:public Person
    {
    public:
        void setMediator(Mediator* mediator)
        {
            m_mediator = mediator;
        }
        void sendMessage(string msg)
        {
            m_mediator->sendMsg(this,msg);
        }
        void getMessage(string msg)
        {
            cout << "房东收到消息!" <<endl;
        }
    
    };
    
    class ClientPerson:public Person
    {
    public:
        void setMediator(Mediator* mediator)
        {
            m_mediator = mediator;
        }
        void sendMessage(string msg)
        {
            m_mediator->sendMsg(this,msg);
        }
        void getMessage(string msg)
        {
            cout << "客户收到消息!" <<endl;
        }
    
    };

    接口使用

    #include "mediator.h"
    
    int main()
    {
        HouseMediator *mediator = new HouseMediator();
        HostPerson *host = new HostPerson();
        host->setMediator(mediator);
        ClientPerson *client = new ClientPerson();
        client->setMediator(mediator);
        mediator->setClient(client);
        mediator->setHost(host);
        client->sendMessage("我要租房子!");
        host->sendMessage("有房子要出租!");
    
        return 0;
    }

    博客参照:

    http://blog.csdn.net/wuzhekai1985/article/details/6673603

  • 相关阅读:
    ant design同时获取下拉框值与文本(选择框)
    nodejs express vue实现文件上传
    Vue路由传参的两种方式
    Vue项目中的接口调用
    表单上传文件 nodejs express Vue (优化)
    httprunner安装可能遇到的问题及解决办法之hrun V查询失败mac
    Eclipse调整编码方式总结
    css水平垂直居中的方法
    手机web前端调试页面的几种方式
    寻找共线特征和寻找缺失值
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3493808.html
Copyright © 2020-2023  润新知