C++中介者模式聊天室案例
C++ 中介者模式聊天室案例
在开发复杂系统时,组件之间的耦合度往往非常高,这不仅增加了代码的维护难度,还可能导致系统的扩展性和可测试性大打折扣。为了解决这一问题,中介者模式应运而生。中介者模式通过引入一个中介对象来协调各个组件之间的交互,从而降低它们之间的耦合度。
什么是中介者模式?
中介者模式是一种行为设计模式,它定义了一个中介对象来封装一系列对象之间的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式的结构
中介者模式通常包含以下几个角色:
- Mediator(中介者):定义一个接口用于与各同事对象通信。
- ConcreteMediator(具体中介者):实现中介者接口,负责协调各个同事对象之间的交互。
- Colleague(同事):每个同事类都知道它的中介者对象,并且与中介者对象通信。
- ConcreteColleague(具体同事):每个具体同事类都实现同事接口,并持有中介者的引用。
聊天室案例
假设我们正在开发一个简单的聊天室应用,用户可以通过发送消息与其他用户进行交流。我们可以使用中介者模式来管理用户之间的通信,确保消息能够正确地从一个用户传递到另一个用户。
实现步骤
- 定义中介者接口
class Mediator {
public:
virtual void sendMessage(const std::string& message, Colleague* colleague) = 0;
};
- 定义具体中介者类
#include <iostream>
#include <unordered_map>
#include <string>
class ChatRoom : public Mediator {
private:
std::unordered_map<std::string, Colleague*> colleagues;
public:
void addColleague(const std::string& name, Colleague* colleague) {
colleagues[name] = colleague;
}
void sendMessage(const std::string& message, Colleague* colleague) override {
for (const auto& pair : colleagues) {
if (pair.second != colleague) {
pair.second->receiveMessage(message);
}
}
}
};
- 定义同事接口
class Colleague {
protected:
Mediator* mediator;
public:
Colleague(Mediator* mediator) : mediator(mediator) {}
virtual void sendMessage(const std::string& message) = 0;
virtual void receiveMessage(const std::string& message) = 0;
};
- 定义具体同事类
class User : public Colleague {
private:
std::string name;
public:
User(Mediator* mediator, const std::string& name) : Colleague(mediator), name(name) {}
void sendMessage(const std::string& message) override {
std::cout << name << " 发送消息: " << message << std::endl;
mediator->sendMessage(message, this);
}
void receiveMessage(const std::string& message) override {
std::cout << name << " 接收消息: " << message << std::endl;
}
};
- 创建并使用聊天室
int main() {
ChatRoom chatRoom;
User user1(&chatRoom, "Alice");
User user2(&chatRoom, "Bob");
User user3(&chatRoom, "Charlie");
chatRoom.addColleague("Alice", &user1);
chatRoom.addColleague("Bob", &user2);
chatRoom.addColleague("Charlie", &user3);
user1.sendMessage("Hello, everyone!");
user2.sendMessage("Hi Alice!");
return 0;
}
运行结果
Alice 发送消息: Hello, everyone!
Bob 接收消息: Hello, everyone!
Charlie 接收消息: Hello, everyone!
Bob 发送消息: Hi Alice!
Alice 接收消息: Hi Alice!
Charlie 接收消息: Hi Alice!
通过上述实现,我们可以看到中介者模式有效地解耦了用户之间的直接通信,使得系统更加灵活和易于扩展。
总结
中介者模式通过引入一个中介对象来协调多个对象之间的交互,降低了它们之间的耦合度。在聊天室案例中,我们展示了如何使用中介者模式来管理用户之间的通信。通过这种方式,我们可以轻松地添加新的用户或修改现有用户的通信方式,而无需修改现有的代码。
文章版权声明:除非注明,否则均为Dark零点博客原创文章,转载或复制请以超链接形式并注明出处。


还没有评论,来说两句吧...