• 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

  • 相关阅读:
    如何使用设计模式系列
    网站性能越来越差怎么办
    ASP.NET特殊字符串替换函数
    SQL Server多事务并发问题
    弹出隐藏子菜单
    过滤sql匹配符号 防止sql注入
    统一建模语言UML轻松入门系列
    sql 字符处理函数大全
    并发控制
    类与类之间的关系图
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3493808.html
Copyright © 2020-2023  润新知