Observer
Problem
Components need to manually check for state changes through polling or passing data through component hierarchies, missing updates. Parent components must explicitly pass callbacks down to children for every possible state change. Adding new subscribers requires modifying existing code. When state updates, there’s no clean way to notify all interested parties without tight coupling.
Solution
Notify interested parties when an object’s state changes rather than having them poll for updates. This creates loose coupling where subjects don’t need to know about their observers.
Example
This example demonstrates the observer pattern where objects can subscribe to be notified of state changes without tight coupling to the subject.
class Observable {
constructor() {
// Store all subscribed observer functions
this.observers = [];
}
subscribe(fn) {
// Add new observer to the list
this.observers.push(fn);
}
notify(data) {
// Notify all observers when state changes
this.observers.forEach(fn => fn(data));
}
}
Benefits
- Creates loose coupling where subjects don’t need to know about their observers.
- Enables reactive updates where components automatically respond to state changes.
- Makes adding new subscribers easy without modifying existing code.
- Eliminates polling by pushing updates to interested parties.
Tradeoffs
- Can create memory leaks if observers aren’t properly unsubscribed.
- Makes data flow harder to trace when updates propagate through many observers.
- May cause performance issues if too many observers react to frequent updates.
- Debugging is harder when trying to track which observer caused a change.