中介者模式——现代C++设计模式

中介者模式——现代C++设计模式


当我们需要创建许多对象,但是不希望知道彼此存在,不能相互调用,该怎么办呢?

介绍

中介者模式中的中介者,可以让各个组件之间的通信更加便利,所以各个组件都应该可以访问中介者,可以以全局静态变量形式、也可以作为各个组件中引用

实现代码

#include<vector>
#include<string>
#include<map>
#include<iostream>
using namespace std;
struct ChatRoom;
struct Person {
    string name;
    ChatRoom* room;
    vector<string>chat_log;
    Person(const string& name) :name{ name } {}
    void receive(const string& origin, const string& message) { //用户收到的信息
        string s{ origin + ": \"" + message + "\"" };         //origin是发送方  message是信息
        cout << "[" << name << "'s chat session]" << s << "\n"; 
        chat_log.emplace_back(s);                            //可以记录下来该用户聊天栏所有信息
    }

    void say(const string& message)const;
    void pm(const string& who, const string& message) const;

};

struct ChatRoom {
    vector <Person*> people;
    void join(Person* p) {
        string join_msg = p->name + " joins the chat";
        broadcast("room", join_msg);
        p->room = this;
        people.push_back(p);
    }
    void broadcast(const string& origin, const string& message) {   //从origin向所有用户发送信息message
        for (auto p : people)
            if (p->name != origin)
                p->receive(origin, message);
    }
    void message(const string& origin, const string& who, const string& message) {   //从origin单独向who发送信息message
        auto target = find_if(begin(people), end(people), [&](const Person* p) {return p->name == who; });
        if (target != end(people)) {
            (*target)->receive(origin, message);
        }

    }
};

void Person::pm(const string& who, const string& message) const { //对某人私聊功能
    room->message(name, who, message);

}
void  Person::say(const string& message)const {                  //向所有人广播的功能
    room->broadcast(name, message);

}

int main()
{
    ChatRoom room;
    Person john{ "john" };
    Person jane{ "jane" };
    room.join(&john);
    room.join(&jane);
    john.say("hi!!!");
    jane.say("hello");
    Person simon{ "simon" };
    room.join(&simon);
    /*
    [john's chat session]room: "jane joins the chat"
    [jane's chat session]john: "hi!!!"
    [john's chat session]jane: "hello"
    [john's chat session]room: "simon joins the chat"
    [jane's chat session]room: "simon joins the chat"
    */
    

    return 0;
}

总结

通过对中介者模式了解之后我们可以观察到,中介者模式通过引入中间组件,让所有对象引用这个中间组件来实现通信。

中介者类似于“服务器”,每个用户之间都通过服务器进行交流,所以典型的Websocket便是中介者模式的一种主要实现方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值