#ifndef BATTLEFIELD_CORE_MESSAGE_BUS_HPP #define BATTLEFIELD_CORE_MESSAGE_BUS_HPP #include #include #include #include #include #include #include namespace battlefield { /// @brief 消息总线中的消息 struct BusMessage { std::string topic; ///< 消息主题 std::string sender; ///< 发送者ID nlohmann::json payload; ///< 消息载荷(JSON) std::string timestamp; ///< 时间戳(ISO 8601) }; /// @brief 消息处理器类型 using MessageHandler = std::function; /// @brief 内部消息总线(设计文档3.1要求:组件间通过内部消息总线协作) /// 实现发布-订阅模式,支持模块解耦、异步处理 class MessageBus { public: /// @brief 获取单例实例 static MessageBus& Instance(); /// @brief 发布消息到指定主题 /// @param topic 主题 /// @param sender 发送者ID /// @param payload 消息载荷 void Publish(const std::string& topic, const std::string& sender, const nlohmann::json& payload); /// @brief 发布简单字符串消息 void PublishString(const std::string& topic, const std::string& sender, const std::string& message); /// @brief 订阅某个主题 /// @param topic 主题 /// @param handler 消息处理器 /// @return 订阅ID(用于取消订阅) int Subscribe(const std::string& topic, MessageHandler handler); /// @brief 取消订阅 /// @param subscriptionId 订阅ID void Unsubscribe(int subscriptionId); /// @brief 获取某个主题的订阅者数量 size_t SubscriberCount(const std::string& topic) const; /// @brief 获取历史消息数 size_t HistoryCount() const { return history_.size(); } private: MessageBus() = default; MessageBus(const MessageBus&) = delete; MessageBus& operator=(const MessageBus&) = delete; /// @brief 生成当前时间戳 static std::string GenerateTimestamp(); int nextSubscriptionId_{1}; std::map> subscriptions_; ///< subscriptionId -> (topic, handler) std::vector history_; ///< 消息历史 }; } // namespace battlefield #endif // BATTLEFIELD_CORE_MESSAGE_BUS_HPP