Lesson 27 / 38
Observer Pattern
Let subscribers react to events without the publisher knowing who they are, using listener interfaces — the pattern behind GUI events, Spring's ApplicationEvent, and pub/sub systems.
Publisher and subscribers
A subject keeps a list of observers and notifies all of them when its state changes, without knowing what each one does. This decouples the event source from the reactions — new observers can be added with zero changes to the subject.
A minimal listener interface
This is the same shape as Swing's ActionListener, Spring's ApplicationListener<OrderPlaced>, or any pub/sub broker — a fixed callback contract plus a list of subscribers.
interface OrderListener { void onPlaced(Order o); }
class OrderService {
private final List<OrderListener> listeners = new ArrayList<>();
void subscribe(OrderListener l) { listeners.add(l); }
void place(Order o) {
// ... persist order ...
listeners.forEach(l -> l.onPlaced(o));
}
}
service.subscribe(order -> emailService.sendReceipt(order));Pattern check
Quick check: What problem does the Observer pattern primarily solve?
- Guaranteeing only one instance of a class exists
- Letting an object notify many interested parties about a change without depending on their concrete types
- Building complex objects step by step
- Choosing which concrete class to instantiate at runtime
Answer
Letting an object notify many interested parties about a change without depending on their concrete types — That's Singleton (0), Builder (2), and Factory (3) respectively — Observer is about one-to-many change notification.