GoF pattern • Behavioral
GoFBehavioralJava example
Observer solves a specific structural problem in the design.
Notify dependents automatically when state changes.
Pattern overview
GoF pattern
Notify dependents automatically when state changes.
Intent
Define a one-to-many dependency so observers are updated automatically when a subject changes.
Problem
Multiple downstream behaviors should react to state changes without the subject knowing concrete listeners.
Solution
Have the subject publish events to subscribed observers.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- For event listeners, domain events, and UI update flows.
Tradeoffs
- Update ordering and failure handling need clear rules.
- Too many implicit listeners can make behavior surprising.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface OrderListener {
void onApproved(String orderId);
}
final class OrderPublisher {
private final List<OrderListener> listeners = new ArrayList<>();
void subscribe(OrderListener listener) {
listeners.add(listener);
}
void approved(String orderId) {
listeners.forEach(listener -> listener.onApproved(orderId));
}
}