Observer Pattern
Define a one-to-many dependency — when one object changes state, dependents update automatically.
📌 Key IdeaSubject maintains observer list; notify pushes changes (push model) or observers pull fresh state. Foundation of event-driven UI, reactive streams, domain events.
Visual
👀 Publish / subscribe
Subject.notifyObservers(event)
│ │
├────────┼──▶ ObserverA.update()
└────────└──▶ ObserverB.update()Decouples publishers from subscribers — add listeners without editing subject.
When to Use
- Model changes must refresh many views / caches / projections.
- Event broadcasting inside a process (
PropertyChangeSupport). - Bridge from domain layer to messaging (*Spring
ApplicationEvent*).
When NOT to Use
- Updates cascade unpredictably — debugging notification storms.
- Cycles — observer triggers subject again without guards.
Anti-Pattern (What NOT to Do)
Subject hard-codes every listener typeBadjava
class Order {
void onShip() {
new EmailService().send(this);
new SmsService().text(this);
// add Slack? edit Order again
}
}You must reopen the core class for every new side effect.
The Right Way
Register / notify (minimal observer API)Goodjava
interface OrderListener { void shipped(Order o); }
class Order {
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
void add(OrderListener l) { listeners.add(l); }
void ship() {
// ...
listeners.forEach(l -> l.shipped(this));
}
}Same idea as
PropertyChangeSupport, Swing listeners, or Spring ApplicationEventPublisher.Pros & Cons
👍 Pros
- Open/Closed — add observers without changing subject.
- Supports MVC-style separation.
👎 Cons
- Unexpected order of notifications — don't rely on ordering unless documented.
- Memory leaks if observers forget to unregister.
Common Confusions Cleared Up
Observer vs Pub/Sub bus
Classic Observer is in-process object graph. Message broker pub/sub is distributed async — same idea at architectural scale.
Interview Q&A
Likely Follow-up Questions
- Cold vs hot observables (Rx) vs classic Observer?
Quick Cheat Sheet
IntentNotify many dependents of change.
JDK
PropertyChangeSupport, Swing listeners.PitfallLeak if observer not removed.