Observer Pattern
In one line
The Observer pattern lets one object (subject) notify a list of dependents (observers) automatically when its state changes.
In simple words
The Observer pattern defines a one-to-many relationship: when one object (the subject) changes state, all registered observers are notified automatically. This is the foundation of event handling, data binding, and reactive programming.
Think of a newsletter: subscribers register with a publisher, and when new content is published, every subscriber gets notified without the publisher needing to know each subscriber individually. The subject maintains a list of observers and calls their update method when something changes.
This pattern decouples the source of changes from the things that react to them. The subject does not need to know what the observers do with the notification — it just broadcasts. JavaScript event listeners, React state subscriptions, and Vue reactivity all use this pattern under the hood.
Example
class Subject {
#observers = [];
subscribe(fn) { this.#observers.push(fn); }
notify(data) { this.#observers.forEach(fn => fn(data)); }
}
const news = new Subject();
news.subscribe(d => console.log("Reader A:", d));
news.subscribe(d => console.log("Reader B:", d));
news.notify("New issue!");
// Reader A: New issue!
// Reader B: New issue!The Subject holds a list of observer functions. notify() calls each one. Subscribers react independently.
Related terms
Related Resources
Related Lessons
- Design Patterns
Observer is a behavioral pattern.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.