What It Is
The Observer pattern lets one object announce events to many subscribers without knowing who they are. Subscribers register once; from then on, every event reaches all of them automatically.
The publisher depends only on a small subscriber interface — new kinds of listeners appear without one line changing in the publisher.
Example: One Alert, Every Subscriber
The monitor keeps an array of subscribers. When something happens, it notifies the whole array — an email alert and a dashboard, today; a chat message tomorrow, by just subscribing it.
Publish once, deliver to all
One alert() call, two deliveries: email to ops@example.com: disk almost full and dashboard shows: disk almost full. The monitor has no idea what an email or a dashboard is — it only knows things that can be notified.
Output: TypeScript file and captured output
interface Subscriber {
notify(event: string): void
}
class EmailAlert implements Subscriber {
private address: string
constructor(address: string) {
this.address = address
}
notify(event: string): void {
console.log("email to", this.address + ":", event)
}
}
class Dashboard implements Subscriber {
notify(event: string): void {
console.log("dashboard shows:", event)
}
}
// The publisher keeps a list and notifies everyone on it.
class Monitor {
private subscribers: Subscriber[] = []
subscribe(subscriber: Subscriber): void {
this.subscribers.push(subscriber)
}
alert(event: string): void {
for (const subscriber of this.subscribers) {
subscriber.notify(event)
}
}
}
const monitor = new Monitor()
monitor.subscribe(new EmailAlert("ops@example.com"))
monitor.subscribe(new Dashboard())
monitor.alert("disk almost full")
When to Use It
Use it when several parts must react to the same events and the list of reactors changes — UI updates, alerting, cache invalidation, activity feeds.
Skip it when exactly one, fixed receiver exists — call it directly. And before writing the list yourself, look at what the platform already gives you: Node.js ships EventEmitter, and browsers have EventTarget — both are this pattern, already written and tested.
Pros and Cons
Pros: publisher and subscribers stay decoupled; subscribers come and go at run time; new reactions need no publisher changes.
Cons: the flow becomes invisible — “who reacts to this?” takes searching; a slow or failing subscriber can stall the notify loop; forgotten unsubscribes leak.