Mediator Pattern

聊天服务器与用户之间的关系,一个用户向另一个用户发送的消息由聊天服务器执行,用户不关注发送细节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Mediator
class User;

class Mediator
{
public:
Mediator() = default;
virtual ~Mediator() = default;

virtual void registerUser(User *user) = 0;
virtual void unregisterUser(User *user) = 0;
virtual bool relayMsg(const std::string &from, const std::string &to, const std::string &msg) = 0;
};

class ChatService : public Mediator
{
public:
ChatService();
~ChatService() override;

void registerUser(User *user) override { m_users.emplace_back(user); }
void unregisterUser(User *user) override { m_users.remove(user); }
bool relayMsg(const std::string &from, const std::string &to, const std::string &msg) override
{
for (User *user : m_users) {
if (user->id() != to) {
continue;
}
user->recv(from, msg);
}
return true;
}

protected:
std::list<User *> m_users;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// User
class Mediator;

class User
{
public:
User() = default;
virtual ~User() = default;

virtual const std::string &id() const = 0;
virtual bool send(const std::string &to, const std::string &msg) = 0;
virtual void recv(const std::string &from, const std::string &msg) = 0;
};

class GeneralUser : public User
{
public:
explicit GeneralUser(const std::string &id, Mediator *mediator = nullptr);
~GeneralUser() override;

const std::string &id() const override { return m_id; }
bool send(const std::string &to, const std::string &msg) override
{
if (m_mediator == nullptr) {
return false;
}
return m_mediator->relayMsg(m_id, to, msg);
}
void recv(const std::string &from, const std::string &msg) override
{
// recived a message
}

protected:
Mediator *m_mediator;
std::string m_id;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// main
#include "mediator.h"
#include "user.h"

int main(int argc, char *argv[])
{
ChatService chatService;
GeneralUser userA("13579", &chatService);
GeneralUser userB("02468", &chatService);
GeneralUser userC("12345", &chatService);

chatService.registerUser(&userA);
chatService.registerUser(&userB);
chatService.registerUser(&userC);

userA.send("02468", "Hello, 02468!");
userA.send("12345", "Hello, 12345!");

userB.send("13579", "Hello, 13579!");
userB.send("12345", "Hello, 12345!");

userC.send("13579", "Hello, 13579!");
userC.send("02468", "Hello, 02468!");

chatService.unregisterUser(&userC);

userA.send("02468", "Hello, 02468!");
userA.send("12345", "Hello, 12345!");

userB.send("13579", "Hello, 13579!");
userB.send("12345", "Hello, 12345!");

return 0;
}

Mediator Pattern
https://laplac2.github.io/design-pattern/mediator/
作者
Laplace
发布于
2023年12月9日
许可协议