Observer
Objects subscribe to a subject and get notified when its state changes - the pattern behind events, bindings, and reactive UIs.
Open this example in StudioObserver defines a one-to-many dependency between objects: one subject holds state, many observers register interest in it, and when the subject's state changes, every registered observer is notified automatically. The subject never knows the concrete types of its observers - only that each one implements a common notification interface.
The problem it solves is a coupling problem. Without Observer, an Account that must trigger fraud checks and send emails ends up importing FraudMonitor and EmailNotifier directly. Every new reaction means editing Account. Observer inverts that: the reactions come to the subject and register themselves, so the subject stays closed while the set of reactions stays open.
Structure
Three roles, all expressible in a plain class diagram:
- Subject - holds the state of interest and a collection of observers. Exposes
attach(observer),detach(observer), and callsnotify()internally after a state change. - Observer - an interface with a single method, conventionally
update(...). - ConcreteObservers - classes implementing
Observer, each encapsulating one reaction.
The link from subject to observers is an ordinary one-to-many association typed against the interface, not against any concrete class. That indirection is the entire pattern.
Worked example: account balance changes
An Account is the subject. A FraudMonitor and an EmailNotifier want to react when the balance changes - this matches the Studio example.
interface AccountObserver {
update(account: Account): void;
}
class Account {
private observers: AccountObserver[] = [];
private balance = 0;
attach(observer: AccountObserver): void {
this.observers.push(observer);
}
detach(observer: AccountObserver): void {
this.observers = this.observers.filter(o => o !== observer);
}
deposit(amount: number): void {
this.balance += amount;
this.notify();
}
getBalance(): number {
return this.balance;
}
private notify(): void {
for (const observer of this.observers) {
observer.update(this);
}
}
}
class FraudMonitor implements AccountObserver {
update(account: Account): void {
if (account.getBalance() > 10_000) {
console.log("Flagging account for review");
}
}
}
class EmailNotifier implements AccountObserver {
update(account: Account): void {
console.log(`Balance is now ${account.getBalance()}`);
}
}
const account = new Account();
account.attach(new FraudMonitor());
account.attach(new EmailNotifier());
account.deposit(15_000); // both observers runAccount compiles without any reference to fraud rules or email. Each observer has exactly one reason to change, which is the Single Responsibility Principle applied to reactions.
Push vs pull
The example above uses the pull model: update receives the subject, and each observer queries what it needs. The alternative, push, sends the changed data in the notification itself: update(newBalance: number).
| Push | Pull | |
|---|---|---|
| Notification payload | The changed data itself | A reference to the subject |
| Observer coupling | To the payload shape | To the subject's query API |
| Efficiency | No extra round trips | Extra calls back into the subject to find out what changed |
| Flexibility | Subject must guess what observers need | Observers take exactly what they want |
Push is efficient when all observers need the same small piece of data. Pull is more flexible when observers need different slices of state, at the cost of a wider subject interface. Neither is formally "correct" - this is a design trade-off, not a rule, and hybrid designs (push an event object, let observers pull the rest) are common in practice.
Why it satisfies the Open-Closed Principle
Adding an audit log, a push notification, or a regulatory report means writing a new class that implements AccountObserver and calling attach. Account is never edited. That is the Open-Closed Principle in its most literal form: the system is open to new behavior through new observer classes, and closed against modification of the subject.
Observer in real systems
The pattern is everywhere, usually under other names:
- UI event listeners -
button.addEventListener("click", handler)is attach; the click is the state change. - Reactive frameworks - RxJS, Vue's reactivity, and property bindings are industrial-strength observer machinery with composition and lifecycle management layered on top.
- Pub/sub messaging - Kafka topics and RabbitMQ exchanges follow the same publish-notify shape.
Known pitfalls
Observer's flexibility has real costs. These failures are specific and recurring:
- Lapsed listeners. An observer that attaches but never detaches is kept alive by the subject's list. In long-lived subjects this is a classic memory leak - one of the most common Observer bugs in UI code. Detach in teardown, or use weak references where the platform supports them.
- Notification order. Most implementations notify in attach order, but that is an accident of the list, not a contract. If
FraudMonitormust run beforeEmailNotifier, plain Observer is a poor fit: it offers no ordering contract, so make the sequence explicit - for example, one coordinating observer that invokes both in order - rather than relying on attach order. - Update cascades and re-entrancy. If an observer mutates the subject inside
update,notifyre-enters while the first notification is still in flight. Best case: redundant notifications. Worst case: infinite loops or observers seeing half-applied state. Guard with a re-entrancy flag, or forbid mutation during notification. - Hidden coupling through side effects. Observers look independent, but if one writes state that another reads, they are coupled through the subject with no visible dependency in the code. The result behaves like global mutable state that only manifests at runtime.
Reach for it
- Multiple independent reactions must follow one state change
- The set of reactions should grow without editing the subject
- Subject and reactions have different change rates or owners
Avoid it
- Exactly one fixed receiver exists and always will
- Reactions must run in a guaranteed order or transactionally
- Observers would need to coordinate with each other through shared state
Practice
Open the observer-pattern example in Studio. Add an AuditLogObserver that records every balance change as a line like 2026-07-10T09:15:00Z balance=15000 - without modifying Account in any way. Then write down what would break if AuditLogObserver had to log the previous balance too, and which model (push or pull) makes that requirement easier to satisfy.