当我们需要创建许多对象,但是不希望知道彼此存在,不能相互调用,该怎么办呢?
介绍
中介者模式中的中介者,可以让各个组件之间的通信更加便利,所以各个组件都应该可以访问中介者,可以以全局静态变量形式、也可以作为各个组件中引用
实现代码
#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便是中介者模式的一种主要实现方式。