Skip to content

觀察者模式

一個 Event Manager,提供兩個操作:

  1. 訂閱
  2. 通知

cpp
#include <thread>
#include <iostream>
#include <functional>
#include <unordered_map>

class EventManager {
public:
    using CBFunc = std::function<void(const std::string&)>;

    EventManager() {
    }

    void subscribe(const std::string& name,
                   const std::string &channelName, CBFunc cb) {
        cbFuncs_[channelName][name] = cb;
    }

    void unsubscribe(const std::string& name, const std::string &channelName) {
        auto it = cbFuncs_.find(channelName);
        if (it == cbFuncs_.end()) {
            return;
        }

        it->second.erase(name);
    }

    void notify(const std::string& channelName, const std::string& msg) {
        auto it = cbFuncs_.find(channelName);
        if (it == cbFuncs_.end()) {
            return;
        }

        for (const auto& [subscriberName, cb]: it->second) {
            cb(msg);
        }
    }

private:
    std::unordered_map<std::string, std::unordered_map<std::string, CBFunc>>
        cbFuncs_;
};

TBD: threading? non-block notify? mpsc queue?

Changelog

Just observe 👀