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
Loading Code Playground...
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?