中介者模式结合事件调度通过事件总线实现对象间解耦,ChatMediator利用EventBus注册和分发消息,使同事对象无需直接引用彼此,提升可维护性与扩展性,适用于GUI、游戏引擎等复杂交互系统。

在C++中,中介者模式(Mediator Pattern)和事件调度机制结合使用,能有效降低多个对象之间的直接耦合,提升系统的可维护性和扩展性。尤其在复杂的交互系统如GUI框架、游戏引擎或模块化应用程序中,这种组合非常实用。
中介者模式通过引入一个“中介者”对象来封装一组对象之间的交互。原本对象之间需要相互引用、直接通信,现在改为全部通过中介者转发消息,从而实现解耦。
典型结构包括:
事件调度是一种发布-订阅模型,允许对象在发生特定事件时广播通知,而无需知道谁会处理它。通过将事件与回调绑定,系统可以在运行时动态响应行为变化。
立即学习“C++免费学习笔记(深入)”;
在C++中,可以使用函数指针、std::function 或信号槽机制(如Boost.Signals2)实现事件调度。
将事件调度集成到中介者中,可以让中介者不再硬编码处理流程,而是根据注册的事件处理器动态响应消息,提高灵活性。
下面是一个简化但实用的C++示例,展示如何将中介者与事件调度结合:
#include <iostream>
#include <functional>
#include <map>
#include <string>
#include <vector>
// 简易事件总线
class EventBus {
public:
using Callback = std::function<void(const std::string&)>;
void on(const std::string& event, const Callback& cb) {
listeners[event].push_back(cb);
}
void emit(const std::string& event, const std::string& data) {
if (listeners.find(event) != listeners.end()) {
for (const auto& cb : listeners[event]) {
cb(data);
}
}
}
private:
std::map<std::string, std::vector<Callback>> listeners;
};
// 中介者实现
class ChatMediator {
public:
ChatMediator() : bus(std::make_unique<EventBus>()) {}
void registerUser(const std::string& name) {
bus->on("send_to_all", [name](const std::string& msg) {
std::cout << "[用户 " << name << " 收到]: " << msg << "\n";
});
}
void sendMessage(const std::string& from, const std::string& msg) {
std::string formatted = from + ": " + msg;
bus->emit("send_to_all", formatted);
}
private:
std::unique_ptr<EventBus> bus;
};
在这个例子中:
EventBus
ChatMediator
这种设计的好处在于:
适用于需要大量对象协作但希望避免网状依赖的系统,比如聊天室、状态同步模块、UI组件通信等。
基本上就这些。通过把中介者作为事件的管理者,而不是直接调用者,能让C++程序更灵活、更接近现代组件化设计思想。
以上就是C++中介者模式与事件调度结合的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号