Observer Design Pattern Explained with Real-World Examples
The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It is the backbone of event-driven programming and is used extensively in UI frameworks, message queues, and notification systems.
When to Use the Observer Pattern
Use the Observer pattern when: • A change in one object requires changing others, and you don't know how many objects need to change. • An object should be able to notify other objects without making assumptions about who those objects are. • You need a publish-subscribe model in your application.
Real-World Example: Stock Price Tracker
interface Observer {
update(stockSymbol: string, price: number): void;
}
interface Subject {
subscribe(observer: Observer): void;
unsubscribe(observer: Observer): void;
notify(): void;
}
class StockExchange implements Subject {
private observers: Observer[] = [];
private prices: Map<string, number> = new Map();
subscribe(observer: Observer) {
this.observers.push(observer);
}
unsubscribe(observer: Observer) {
this.observers = this.observers.filter(o => o !== observer);
}
setPrice(symbol: string, price: number) {
this.prices.set(symbol, price);
this.notifyAll(symbol, price);
}
private notifyAll(symbol: string, price: number) {
this.observers.forEach(o => o.update(symbol, price));
}
}
class MobileApp implements Observer {
update(symbol: string, price: number) {
console.log(`📱 Mobile Alert: ${symbol} is now $${price}`);
}
}
class EmailService implements Observer {
update(symbol: string, price: number) {
console.log(`📧 Email: ${symbol} price changed to $${price}`);
}
}How React Uses the Observer Pattern
React's state management is built on the Observer pattern. When you call setState or use a state hook, React's reconciler (the subject) notifies all subscribing components (observers) to re-render. Libraries like Redux, Zustand, and MobX are all implementations of the Observer pattern.
Key Takeaways
The Observer pattern is fundamental to modern software development. It enables loose coupling between components, makes systems more maintainable, and is the foundation of reactive and event-driven architectures. Master this pattern and you will see it everywhere — from DOM event listeners to Kafka consumers to webhook systems.