👀 Observer Pattern — React to Change Automatically
Category: general / design-patterns
Difficulty: medium
Use this guide as a quick-reference for interviews or design discussions. 1️⃣ Core Idea The Observer Pattern (also known as the Pub/Sub Pattern ) is a behavioral design pattern in which a subject (publisher) maintains a list of observers (subscribers) and notifies them automatically whenever a state change or event occurs. [code example] This pattern promotes loose coupling between the subject and the observers, facilitating clean, modular design — a fundamental principle of event-driven programming. 2️⃣ JavaScript & Event-Driven Programming JavaScript is one of the most event-driven programming languages. We frequently use the Observer Pattern via event listeners : [code example] ✅ The browser’s event system is a natural example of the observer pattern in action. 3️⃣ Basic Implementation 3.1 Simple Observer System [code example] Output: [code example] 4️⃣ Advanced Version: Multi-Mode Event Hub Inspired by a Coursera interview, here's an advanced Observer implementation supporting: subscribe() subscribeOnce() subscribeOnceAsync() publish() publishAll() [code example] Sample Test [code example] 5️⃣ Observer vs Pub-Sub Observer Subject holds observer references Direct method call MVC apps, local state updates 6️⃣ Pros & Cons ⚠️ Drawbacks May cause memory leaks (unremoved observers) Supports dynamic notification Complex state sync in larger apps | 7️⃣ Interview Q&A Q1: What is the Observer Pattern? A: It’s a behavioral pattern where an object (subject) notifies a list of observers when a change in state occurs. Q2: Difference between Observer and Pub/Sub? A: In Observer, the subject knows the observers directly. In Pub/Sub, they are decoupled via a message broker or event bus. Q3: How does JavaScript use the Observer Pattern? A: Through event listeners (addEventListener, onClick), state libraries like Redux, and libraries like RxJS. Q4: When is Observer not a good fit? A: In highly decoupled systems where components should not know about each other; use Pub/Sub instead...