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.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?