Observer
Observer lets objects subscribe to events. The subject notifies all observers when its state changes. Publishers do not hard-code the listeners.
Detailed Explanation
A button does not know about logging and metrics. It holds a list of listeners and calls onClick on each. New behaviour is a new listener, not an edit to the button. That is observer, also called publish-subscribe when the channel is a bus.
Java's java.util.Observer / Observable are obsolete. Write an interface (OrderListener) and a list. CopyOnWriteArrayList is a good list when listeners register from other threads and you fire often. Swing used this everywhere. Reactive streams and message brokers are the same idea at a distance.
Notification can be push (event object) or pull (observers query the subject). Push is usual. Synchronous notify runs listeners on the subject's thread: a slow listener stalls the rest. An executor can decouple. Exceptions in a listener should not cancel the others unless you decide that; catch and log per listener.
You reach for observer when many independent reactions share one event. You reach for a direct call when there is one consumer. You reach for a queue when the consumer must not run on the producer thread.
The cost of forgotten unsubscribe is a leak: the subject retains the observer. The cost of notifying under a lock is deadlock if a listener calls back into the subject. Copy the listener list, drop the lock, then fire. The cost of a huge event object is allocation on a hot path.
Do not use observer as a hidden global bus for everything; the graph becomes unreadable. Named events and a small number of subjects stay clear.
Code Examples
import java.util.ArrayList;
import java.util.List;
interface Listener {
void onPay(int paise);
}
class Register {
private final List<Listener> listeners = new ArrayList<>();
void add(Listener l) {
listeners.add(l);
}
void pay(int paise) {
for (Listener l : List.copyOf(listeners)) { // snapshot
l.onPay(paise);
}
}
public static void main(String[] args) {
Register r = new Register();
r.add(p -> System.out.println("paid " + p));
r.pay(50); // prints: paid 50
}
}Common Gotchas
`java.util.Observable` is deprecated
write your own list.
Forgetting to remove a listener leaks the observer
Forgetting to remove a listener leaks the observer