How do I implement Observer pattern?

The Observer pattern is a behavioral design pattern that lets you define a one-to-many dependency between objects. When one object changes state, all its dependents are notified and updated automatically. This pattern is commonly used in applications where the state of one object needs to be reflected in multiple other objects.

Example of Observer Pattern in C++

#include 
#include 
#include 

// Forward declaration of Observer class
class Observer;

// Subject class
class Subject {
public:
    virtual void attach(Observer* observer) = 0;
    virtual void detach(Observer* observer) = 0;
    virtual void notify() = 0;
};

// Observer class
class Observer {
public:
    virtual void update(int value) = 0;
};

// Concrete Subject class
class ConcreteSubject : public Subject {
private:
    std::vector observers;
    int state;

public:
    void attach(Observer* observer) override {
        observers.push_back(observer);
    }

    void detach(Observer* observer) override {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }

    void notify() override {
        for (Observer* observer : observers) {
            observer->update(state);
        }
    }

    void setState(int value) {
        state = value;
        notify();
    }
};

// Concrete Observer class
class ConcreteObserver : public Observer {
private:
    int observerState;

public:
    void update(int value) override {
        observerState = value;
        std::cout << "Observer state updated to: " << observerState << std::endl;
    }
};

int main() {
    ConcreteSubject subject;
    ConcreteObserver observer1;
    ConcreteObserver observer2;

    subject.attach(&observer1);
    subject.attach(&observer2);

    subject.setState(1); // Both observers' state will be updated
    subject.setState(2); // Both observers' state will be updated

    return 0;
}
        

Observer pattern design patterns C++ software design behavioral patterns