Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Use when a change to one object requires updating others and you don't want these objects tightly coupled, or when an object should notify others without knowing who they are.
Examples:
- A customer wants to know when a new iPhone arrives at a store. Instead of visiting daily (polling) or the store spamming every customer by email (broadcast), the Observer pattern lets the customer subscribe to the store's arrival events and unsubscribe when no longer interested — notifying only those who asked.
class Subject {
vector<Observer*> observers;
public:
void Attach(Observer* o) { observers.push_back(o); }
void Notify() { for (auto o : observers) o->Update(); }
};
class Observer {
public:
virtual void Update() = 0;
};
class ConcreteObserver : public Observer {
void Update() override { /* pull state from subject */ }
};
Synonyms: dependents, publish-subscribe, event-subscriber, listener