Observer Pattern
Notify multiple objects about state changes automatically
Pattern Overview
🎭 The Observer Pattern - Event Notification System
Defines a one-to-many dependency between objects so that when one object changes state, all dependents are notified automatically!
- Core Problem Solved:
- Decouple objects that need to communicate
- Notify multiple objects of state changes
- Support dynamic subscription/unsubscription
- Enable reactive programming patterns
- Interface-based: Traditional OOP with observer interfaces
- Event-driven: Using JavaScript's EventTarget API
- Reactive: Modern observables with functional operators
- Real-World Applications:
- Newsletter and notification systems
- Model-View-Controller architectures
- Real-time data feeds (stocks, chat)
- DOM event handling
- React state management
- WebSocket communication
- Modern Framework Usage:
- React hooks (useState, useEffect)
- Vue.js reactive data system
- Angular observables (RxJS)
- Node.js EventEmitter pattern
Examples:
Email newsletter - notify all subscribers when new article is published
Input:
newsletter.subscribe(emailSubscriber)Output:
Subscriber added to newsletterStock trading app - update all UI components when price changes
Input:
stockTracker.setPrice('AAPL', 150)Output:
Price change event firedReal-time data - react to streaming updates with functional approach
Input:
observable.subscribe(value => console.log(value))Output:
Observer function registeredData transformation - chain operations on streaming data
Input:
observable.map(x => x * 2).filter(x => x > 10)Output:
Transformed observable chainConcepts
One-to-Many DependencyEvent NotificationSubscribe/UnsubscribeLoose CouplingState Broadcasting
Complexity Analysis
Time:O(n) - notify all observers
Space:O(n) - store observer references
Implementation
NewsletterService
Time: O(n) | Space: O(n)
class NewsletterService {
private subscribers: Observer<string>[] = [];
subscribe(observer: Observer<string>): void {
this.subscribers.push(observer);
}
notify(news: string): void {
this.subscribers.forEach(observer => observer.update(news));
}
}