November 25, 202611 minutes
A delayed flight, a bookshop sign-up sheet and a dark-mode toggle. Learn how the Observer pattern lets one object announce changes without knowing who listens, with diagrams, Java code and a narrated video.
Your flight is delayed by forty minutes. Within seconds the departure board flips, your phone buzzes with a text, and the crew gets a new schedule. One thing changed, and three different systems reacted, each in its own way. Next month a loyalty app wants to know too, then a baggage system. How do you write a flight that tells them all, without knowing any of them? The answer has a name: the Observer pattern.
Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.
One status change on flight QX 405, and three systems react differently: the board shows the new status, the passengers get a text, the crew roster moves everybody’s call time. And the list keeps growing.
Leave the airport for a minute and walk into a small bookshop. Volume three of a popular series arrives some day next week, and a dozen fans want a copy on the day it lands. The shopkeeper knows when the box arrives; the fans don’t.
In pattern words, the one that changes is the subject (the shopkeeper), and the ones who need to hear about it are the observers (the fans). Back at the airport, the flight is the subject, and the board, the texts and the crew roster are its observers.
There are two obvious ways to spread the news. The first: the fans keep asking. Every morning they walk in: is it here yet? In code, that’s polling: every screen checks the flight’s status on a timer and updates itself when something changed.
String lastSeen = "";
while (true) {
String now = flight.status();
if (!now.equals(lastSeen)) {
show(now);
lastSeen = now;
}
Thread.sleep(5000);
}It’s simple, and it works. But a thousand screens asking every five seconds is two hundred questions a second, almost every answer is “no”, and the news still arrives up to five seconds late.
The second way: the shopkeeper knows every regular by name and phones each one personally
when the box arrives. In code, the flight calls each system by name, right inside setStatus:
class Flight {
private final String code = "QX 405";
private final DepartureBoard board = new DepartureBoard();
private final PassengerSms sms = new PassengerSms();
private final CrewRoster crew = new CrewRoster();
private String status = "ON TIME";
void setStatus(String newStatus) {
status = newStatus;
board.show(code, status);
sms.textAll(code, status);
crew.reschedule(code);
}
}Be fair to this version. It’s direct, you can read exactly what happens, and a debugger walks right through it. For one or two fixed listeners, it’s fine.
Then the requests come in. The loyalty app wants delay alerts: a new field and a new line in
Flight. Texts need an off switch: now the flight checks a flag before every message. Baggage
wants to re-tag the bags: another field, another import, another line. Here is setStatus after
those three requests:
void setStatus(String newStatus) {
status = newStatus;
board.show(code, status);
if (smsEnabled) sms.textAll(code, status);
crew.reschedule(code);
loyalty.pushAlert(code, status);
baggage.retag(code);
}Now the flight depends on five classes that have nothing to do with flying. You can’t test it without them, and you can’t add or drop one while the program runs.
It’s the shopkeeper learning a new name and a new routine for every regular. The calls aren’t the problem. The subject knows too much.
So the shopkeeper puts a clipboard on the counter. Want a call when volume three arrives? Write down your name and number. When the box arrives, the shopkeeper calls down the sheet. No need to know who you are, only that you left a number.
That’s the whole idea. The subject keeps a list of anyone who signed up, through one tiny interface, and announces each change to that list. It never names a listener class. The Gang of Four describe it as a one-to-many dependency: when one object changes state, all its dependents are notified and updated automatically.
Know the list, not the listeners.
We need three pieces.
First, the phone number: an interface with one method. This is all an observer has to offer:
interface FlightListener {
void onStatusChanged(Flight flight);
}Second, the subject. The flight holds a list of flight listeners (the sheet). subscribe adds
a name to the sheet, unsubscribe crosses it off again, and setStatus changes the status, then
walks the list and calls each listener, passing itself along:
class Flight {
private final List<FlightListener> listeners = new ArrayList<>();
private final String code;
private String status = "ON TIME";
Flight(String code) { this.code = code; }
void subscribe(FlightListener l) { listeners.add(l); }
void unsubscribe(FlightListener l) { listeners.remove(l); }
void setStatus(String newStatus) {
status = newStatus;
for (FlightListener l : listeners) {
l.onStatusChanged(this);
}
}
String code() { return code; }
String status() { return status; }
}Third, the observers. The board shows the new status, and the text service sends a message. Each one decides what to do:
class DepartureBoard implements FlightListener {
public void onStatusChanged(Flight f) {
show(f.code(), f.status());
}
}
class PassengerSms implements FlightListener {
public void onStatusChanged(Flight f) {
textAll(f.code() + " is now " + f.status());
}
}Now the wiring. Outside the flight, we subscribe the board, the texts and the crew; then one status
change reaches all three. The loyalty app is one more subscribe, written as a lambda, since the
interface has one method. The Flight class doesn’t change at all.
Flight flight = new Flight("QX 405");
flight.subscribe(new DepartureBoard());
flight.subscribe(new PassengerSms());
flight.subscribe(new CrewRoster());
flight.setStatus("DELAYED 40");
flight.subscribe(f -> loyalty.alert(f.code()));One design choice is what the call carries. The shopkeeper could say: volume three is in, it’s forty dollars, I’ve put one aside. That’s push: the subject sends the details. Or only: “It’s in.” You ask about what you care about. That’s pull, and it’s what our flight does: it passes itself, and each observer asks for what it needs.
// push: the subject sends the details
void onStatusChanged(String code, String oldStatus, String newStatus);
// pull: the subject sends itself; observers ask
void onStatusChanged(Flight flight);| Push | Pull | |
|---|---|---|
| The call carries | every detail | only “I changed” (the subject) |
| Observers | get everything, even what they don’t need | ask for exactly what they need |
| When a new detail appears | the interface changes | the interface stays the same |
| Coupling | observers know the event’s fields | observers know the subject’s getters |
| Suits | small, fixed events | observers that each want something different |
Neither is wrong. And subscriptions change while the program runs: texts off? Unsubscribe the text service. Back on? Subscribe it again. There’s no flag in the flight.
Now a mistake that’s easy to make. The airline app has a track this flight button, and each tap opens a screen that subscribes to the flight:
class FlightTracker implements FlightListener { // one per open app screen
private final Flight flight;
FlightTracker(Flight flight) {
this.flight = flight;
flight.subscribe(this);
}
public void onStatusChanged(Flight f) { refresh(f.status()); }
void close() { /* screen gone, still on the list */ }
}The passenger closes the screen, but close() never unsubscribes from the flight. The flight’s
list still holds the tracker, so the garbage collector can’t free it. A thousand passengers later,
the list holds a thousand dead screens, and every delay still updates them all. That’s a memory
leak, and it has a name: the lapsed listener. (Joshua Bloch lists listeners and callbacks as a
common source of memory leaks in Effective Java.)
On the clipboard, those are names of people who moved away: the sheet only grows, and the
shopkeeper keeps calling numbers nobody answers. The fix is one line: close unsubscribes.
void close() { flight.unsubscribe(this); }Sign up. Sign off.
Two more details. If you can’t guarantee a matching unsubscribe, a subject can hold its listeners
through weak references so forgotten ones can be collected (the usual mitigation for the lapsed
listener problem). And an observer that unsubscribes during a notification would modify the
ArrayList while the for loop walks it, which throws ConcurrentModificationException; iterate
over a copy, or use a CopyOnWriteArrayList, if listeners may leave mid-broadcast.
The second trap is order. Our list happens to call listeners in sign-up order, but that’s a
detail of ArrayList, not a promise. Java’s old java.util.Observable class even documents that
“the order in which notifications will be delivered is unspecified.” So if the crew roster must
update before the texts go out, those aren’t two observers. That’s a sequence, so write it as one.
You’ve used this pattern already. A Swing button takes any number of action listeners and calls them all on a click:
saveButton.addActionListener(e -> document.save());For your own classes, Java has a ready-made sign-up sheet: java.beans.PropertyChangeSupport.
Here it backs an app’s settings:
class Settings {
private final PropertyChangeSupport changes = new PropertyChangeSupport(this);
private String theme = "light";
void addListener(PropertyChangeListener l) {
changes.addPropertyChangeListener(l);
}
void setTheme(String newTheme) {
String old = theme;
theme = newTheme;
changes.firePropertyChange("theme", old, newTheme);
}
}When the theme changes, firePropertyChange pushes three things: the property name, the old
value and the new value. Two listeners subscribe as lambdas; switch to dark mode, and every window
repaints, and the choice is saved for next time:
settings.addListener(e -> window.repaint());
settings.addListener(e -> prefs.save("theme", e.getNewValue()));Pick dark again, and nothing fires: when the old and new values are equal (and not null), no event goes out.
The old java.util.Observable class has been deprecated since Java 9 (its own notes cite the
limited event model and the unspecified order, and point to java.beans and the Flow API). Use
PropertyChangeSupport, or a small list like the flight’s.
Observer is often confused with publish-subscribe. The Gang of Four even give publish-subscribe as another name for Observer. Today the words usually mean something bigger:
flights, subscribers sign up with the broker, and the two sides never meet. Delivery is often
asynchronous and crosses services.In the bookshop, that’s a town-wide text service for new books: you subscribe to manga, not to one shop, and no shop ever sees your number.
| Observer | Publish-subscribe | |
|---|---|---|
| Who keeps the subscriptions | the subject | a broker (event bus, message queue) |
| Do the two sides know each other? | the subject holds references to observers | no, only the topic |
| Typical delivery | direct, synchronous, same process | often asynchronous, across services |
| Survives a crash? | no | depends on the broker (often durable) |
Observer keeps the list. Publish subscribe hands it to a broker.
Use Observer when one change has to reach several others, when that set varies or isn’t known yet, and when the subject shouldn’t depend on them. User interfaces, models with their views (the classic Model-View-Controller), and domain events are the classic places for it.
Skip it for one fixed listener: call it directly (nobody puts out a sign-up sheet for their one business partner). Skip it when steps must run in order, like charge the card, then email the receipt. And when delivery must survive a crash, use a broker. Finally, watch for chains: an observer that changes another subject, which notifies its own observers, is hard to follow.
Know the list, not the listeners.
Related patterns: the Decorator pattern also works through one shared interface, but wraps a single object instead of broadcasting to many; the Strategy pattern plugs in one interchangeable algorithm; the Command pattern turns a call into an object you can queue or undo; and in a Chain of Responsibility one handler takes the request, while in Observer every listener hears it.