JavaScript
/Advanced
Observer Pattern
Definition
A behavioral design pattern where an object (the Subject) maintains a list of its dependents (Observers) and automatically notifies them of any state changes, usually by calling one of their methods.
Explain Like I'm New
The Observer pattern is a YouTube channel. The Subject is the YouTuber. The Observers are the subscribers. The subscribers say 'Hey, let me know when you upload.' When the YouTuber uploads a video, they don't manually message every single person; the system iterates through the subscriber list and sends everyone a notification.
Real World Example
React's `useEffect` listening to state changes. Vue's reactivity system. Standard DOM event listeners (`element.addEventListener('click', fn)`).
Common Use Cases
- •Event-driven architectures
- •Decoupling complex UI updates
Interactive Example
class YouTubeChannel { // The Subject constructor() { this.subscribers = []; } subscribe(callback) { this.subscribers.push(callback); // Return an unsubscribe function return () => { this.subscribers = this.subscribers.filter(sub => sub !== callback); }; } uploadVideo(title) { console.log(`Uploaded: ${title}. Notifying subs...`); // Notify all observers this.subscribers.forEach(callback => callback(title)); } } const channel = new YouTubeChannel(); // Observer 1 const unsubAlice = channel.subscribe(video => console.log(`Alice got pinged: ${video}`)); // Observer 2 channel.subscribe(video => console.log(`Bob got pinged: ${video}`)); channel.uploadVideo("JS Patterns Explained"); // Alice unsubscribes unsubAlice(); channel.uploadVideo("React Hooks"); // Only Bob gets pinged
Interview Questions
basic
- What are the two main roles in the Observer pattern?
intermediate
- What is the difference between the Observer pattern and the Pub-Sub pattern?
advanced
- How do you prevent memory leaks when using the Observer pattern?