Observer Pattern

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.

Who told them all?

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.

A status change on flight QX 405 to DELAYED 40 reaches three systems: the departure board shows it, passenger SMS sends a text, and the crew roster reschedules; a loyalty app and a baggage system are waiting to be added. A status change on flight QX 405 to DELAYED 40 reaches three systems: the departure board shows it, passenger SMS sends a text, and the crew roster reschedules; a loyalty app and a baggage system are waiting to be added.
One change, many parties that care, and more of them every month.

A bookshop waiting for volume three

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.

The analogy mapped onto the example: the shopkeeper is the subject, like the Flight; the fans are the observers, like the departure board, the passenger SMS and the crew roster. The analogy mapped onto the example: the shopkeeper is the subject, like the Flight; the fans are the observers, like the departure board, the passenger SMS and the crew roster.
One subject, many observers.

The obvious ways

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.

Why it breaks: every newcomer edits the flight

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.

The Flight class depends directly on five classes: DepartureBoard, PassengerSms, CrewRoster, LoyaltyApp and Baggage; every new interested party means editing Flight, Flight can't be tested alone, and the set is fixed at compile time. The Flight class depends directly on five classes: DepartureBoard, PassengerSms, CrewRoster, LoyaltyApp and Baggage; every new interested party means editing Flight, Flight can't be tested alone, and the set is fixed at compile time.
The subject knows too much: it names every listener.

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.

The key insight: a sign-up sheet

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.

Before: Flight points at five concrete classes. After: Flight keeps a list of FlightListener, and DepartureBoard, PassengerSms, CrewRoster and LoyaltyApp each subscribe to that list; the arrows now point from the observers to the subject. Before: Flight points at five concrete classes. After: Flight keeps a list of FlightListener, and DepartureBoard, PassengerSms, CrewRoster and LoyaltyApp each subscribe to that list; the arrows now point from the observers to the subject.
Flip who knows whom: observers sign up; the subject only knows the list.

Know the list, not the listeners.

Building it

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()));
Class diagram: Flight holds a list of FlightListener and has subscribe, unsubscribe and setStatus; FlightListener is an interface with onStatusChanged(Flight); DepartureBoard, PassengerSms and CrewRoster implement it, and a lambda can implement it too. Class diagram: Flight holds a list of FlightListener and has subscribe, unsubscribe and setStatus; FlightListener is an interface with onStatusChanged(Flight); DepartureBoard, PassengerSms and CrewRoster implement it, and a lambda can implement it too.
Observer: a subject with a list, one listener interface, any number of implementations.
Sequence: setStatus DELAYED 40 runs on the Flight; the Flight calls onStatusChanged on the DepartureBoard, then PassengerSms, then CrewRoster, then the loyalty lambda; each reads code and status back from the flight. Sequence: setStatus DELAYED 40 runs on the Flight; the Flight calls onStatusChanged on the DepartureBoard, then PassengerSms, then CrewRoster, then the loyalty lambda; each reads code and status back from the flight.
One status change, announced to everyone on the list.

Push or pull

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);
PushPull
The call carriesevery detailonly “I changed” (the subject)
Observersget everything, even what they don’t needask for exactly what they need
When a new detail appearsthe interface changesthe interface stays the same
Couplingobservers know the event’s fieldsobservers know the subject’s getters
Suitssmall, fixed eventsobservers 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.

Two traps: forgotten listeners and notification order

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.)

The flight's listener list holds the board, SMS, crew and loyalty listeners plus a thousand closed FlightTracker screens; every status change still visits all 1,004 entries, and none of the closed screens can be garbage collected. The flight's listener list holds the board, SMS, crew and loyalty listeners plus a thousand closed FlightTracker screens; every status change still visits all 1,004 entries, and none of the closed screens can be garbage collected.
Closed, but still on the list: 1,004 listeners instead of 4.

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.

A realistic example: settings that repaint every window

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.

Sequence: dark mode is chosen; Settings.setTheme calls firePropertyChange with theme, light, dark; PropertyChangeSupport calls the repaint listener and the save listener; a second setTheme dark fires nothing because old and new are equal. Sequence: dark mode is chosen; Settings.setTheme calls firePropertyChange with theme, light, dark; PropertyChangeSupport calls the repaint listener and the save listener; a second setTheme dark fires nothing because old and new are equal.
PropertyChangeSupport keeps the list and pushes name, old value and new value.

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 vs publish-subscribe

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:

  • In Observer, the subject keeps the list itself and calls each observer directly, in the same program, right away.
  • In publish-subscribe, a broker sits in the middle. The flight publishes to a topic called 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: Flight holds the listener list and calls DepartureBoard, PassengerSms and CrewRoster directly. Publish-subscribe: Flight publishes to a broker topic called flights; service A, service B and service C subscribe to the broker and never reference Flight. Observer: Flight holds the listener list and calls DepartureBoard, PassengerSms and CrewRoster directly. Publish-subscribe: Flight publishes to a broker topic called flights; service A, service B and service C subscribe to the broker and never reference Flight.
Observer keeps the list. Publish subscribe hands it to a broker.
ObserverPublish-subscribe
Who keeps the subscriptionsthe subjecta broker (event bus, message queue)
Do the two sides know each other?the subject holds references to observersno, only the topic
Typical deliverydirect, synchronous, same processoften asynchronous, across services
Survives a crash?nodepends on the broker (often durable)

Observer keeps the list. Publish subscribe hands it to a broker.

When to use it (and when not to)

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.

Decision flowchart: if only one fixed object needs to know, call it directly; if the steps must run in a specific order, write a sequence; if delivery must survive a crash or cross services, use a broker; otherwise use the Observer pattern, and keep updates from cascading. Decision flowchart: if only one fixed object needs to know, call it directly; if the steps must run in a specific order, write a sequence; if delivery must survive a crash or cross services, use a broker; otherwise use the Observer pattern, and keep updates from cascading.
When Observer pays for itself.

Recap

  • The subject keeps a list of listeners behind one small interface.
  • Observers subscribe from outside, and can unsubscribe while the program runs.
  • Each change is announced to the list, pushed or pulled.
  • Every subscribe needs an unsubscribe, or the list leaks.
  • Don’t rely on notification order; if order matters, write a sequence.
  • A broker in the middle makes it publish-subscribe.
Recap chain: a list behind one interface, observers subscribe from outside, announce each change to the list, every subscribe needs an unsubscribe. Recap chain: a list behind one interface, observers subscribe from outside, announce each change to the list, every subscribe needs an unsubscribe.
The flight never learned a single name.

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.