Observer
Objects subscribe to a subject and get notified automatically when it changes — the subject never needs to know who's listening.
Intent & Description
🎯 Intent
Automatically notify any number of interested objects when something changes, without hard-coding who those objects are.
📋 Context
You’re building a stock ticker, event system, real-time UI updates, or anything where one state change needs to ripple to multiple consumers. Polling is wasteful; direct coupling is brittle.
💡 Solution
A Subject maintains a list of Observer subscribers. When state changes, it calls notify() on all of them. Observers subscribe and unsubscribe at runtime. The Subject doesn’t know or care which Observers are attached — just that they implement update().
Real-world Use Case
Source
📌 TL;DR
Subject changes → all subscribers get notified automatically. Fully decoupled. The foundation of every event system and reactive framework. Notification order is undefined — design around that.
Advantages
- Add new subscriber types without touching the subject’s code.
- Subscribe and unsubscribe at runtime — fully dynamic relationships.
Disadvantages
- Notification order is undefined — if subscribers depend on being called in a specific sequence, you’ll have subtle bugs.
class Subject {
constructor() { this.observers = []; }
subscribe(observer) { this.observers.push(observer); }
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(obs => obs.update(data));
}
}