Build event-driven systems with loose coupling
Imagine you have a shopping cart. When items change:
Without Observer: Each component directly calls the others. Tight coupling nightmare.
One-to-many dependency where changes in one object automatically notify all dependents.
// When the subject changes...
subject.notify()
// ...all observers get updated automatically
// No tight coupling required!
Flow: Subject state changes → notify() called → All observers updated
interface Observer {
update(data: any): void
}
class Subject {
private observers = new Set<Observer>()
attach(observer: Observer): void {
this.observers.add(observer)
}
detach(observer: Observer): void {
this.observers.delete(observer)
}
notify(data: any): void {
this.observers.forEach(obs => obs.update(data))
}
}
class ShoppingCart extends Subject {
private items: string[] = []
addItem(item: string) {
this.items.push(item)
this.notify({ items: this.items, action: 'add' })
}
}
class EmailObserver implements Observer {
update(data: any) {
console.log(`Sending email: Item ${data.action}ed`)
}
}
class AnalyticsObserver implements Observer {
update(data: any) {
console.log(`Tracking: ${data.items.length} items`)
}
}
button.addEventListener('click', handler)
Model notifies View of data changes
RxJS Observables, React state management
Price changes notify all dashboard widgets
Remember: The Observer pattern is everywhere in modern development - from DOM events to reactive state management.
Start using it when you find yourself writing notification code!