BehavioralC++verifiedVerified

Observer Pattern in C++

Defines a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.

How to Implement the Observer Pattern in C++

1Step 1: Define the event and callback types

using Callback = std::function<void(const std::string&)>;

class EventEmitter {
    struct Listener {
        int id;
        std::string event;
        Callback cb;
    };

    std::vector<Listener> listeners_;
    int nextId_ = 0;

public:

2Step 2: Subscribe and unsubscribe

    int on(const std::string& event, Callback cb) {
        int id = nextId_++;
        listeners_.push_back({id, event, std::move(cb)});
        return id;
    }

    void off(int id) {
        std::erase_if(listeners_, [id](const Listener& l) { return l.id == id; });
    }

3Step 3: Emit event to all matching listeners

    void emit(const std::string& event, const std::string& data) {
        for (const auto& l : listeners_)
            if (l.event == event) l.cb(data);
    }
};

4Step 4: Demonstrate

int main() {
    EventEmitter emitter;
    int id = emitter.on("message", [](const std::string& data) {
        std::cout << "Received: " << data << "\n";
    });

    emitter.emit("message", "Hello!");
    emitter.off(id);
    emitter.emit("message", "This won't print");
}

Observer Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Observer Pattern in the Real World

Think of a newspaper subscription service. The publisher (subject) doesn't know exactly who its subscribers (observers) are—it just maintains a list. When a new edition is printed, it delivers a copy to every subscriber on the list automatically. Subscribers can cancel at any time without the publisher needing to change anything.