# Observer PatternA 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**.

{{< lesson-video youtube="oP3R3QlbdZ0" title="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.

```mermaid {alt="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." caption="One change, many parties that care, and more of them every month."}
flowchart LR
  F(["Flight QX 405<br/>DELAYED 40"]) --> B["departure board<br/>shows it"]
  F --> S["passenger SMS<br/>texts everyone"]
  F --> C["crew roster<br/>reschedules"]
  F -.-> L["loyalty app?"]
  F -.-> G["baggage?"]
  class F c6
  class B c5
  class S c4
  class L,G muted
```

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

```mermaid {alt="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." caption="One subject, many observers."}
flowchart LR
  subgraph shop["Bookshop"]
    direction TB
    K["shopkeeper<br/>(knows when the box arrives)"] --> FA["a dozen fans<br/>(want to know)"]
  end
  subgraph air["Airport"]
    direction TB
    FL["Flight<br/>(subject)"] --> OB["board · SMS · crew<br/>(observers)"]
  end
  shop ~~~ air
  class K,FL c6
```

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

```java
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`:

```java
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:

```java
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.

```mermaid {alt="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." caption="The subject knows too much: it names every listener."}
flowchart LR
  F["Flight"] --> B["DepartureBoard"]
  F --> S["PassengerSms"]
  F --> C["CrewRoster"]
  F --> L["LoyaltyApp"]
  F --> G["Baggage"]
  class F c6
  class B,S,C,L,G bad
```

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.

```mermaid {alt="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." caption="Flip who knows whom: observers sign up; the subject only knows the list."}
flowchart TB
  subgraph before["Before: hard-wired"]
    direction TB
    F1["Flight"] --> X1["DepartureBoard"]
    F1 --> X2["PassengerSms"]
    F1 --> X3["CrewRoster"]
  end
  subgraph after["After: a sign-up sheet"]
    direction TB
    Y1["DepartureBoard"] -->|subscribe| LS["Flight<br/>(list of FlightListener)"]
    Y2["PassengerSms"] -->|subscribe| LS
    Y3["CrewRoster"] -->|subscribe| LS
  end
  before ~~~ after
  class F1,LS c6
  class X1,X2,X3 bad
  class Y1,Y2,Y3 good
```

> **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:

```java
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:

```java
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:

```java
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.**

```java
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()));
```

```mermaid {alt="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." caption="Observer: a subject with a list, one listener interface, any number of implementations."}
classDiagram
  class Flight {
    -List~FlightListener~ listeners
    +subscribe(FlightListener l)
    +unsubscribe(FlightListener l)
    +setStatus(String newStatus)
    +code() String
    +status() String
  }
  class FlightListener {
    <<interface>>
    +onStatusChanged(Flight flight)
  }
  Flight o--> FlightListener : notifies
  FlightListener <|.. DepartureBoard
  FlightListener <|.. PassengerSms
  FlightListener <|.. CrewRoster
  note for FlightListener "one method, so a lambda fits"
```

```mermaid {alt="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." caption="One status change, announced to everyone on the list."}
sequenceDiagram
  participant F as Flight
  participant B as board
  participant S as SMS
  participant C as crew
  Note over F: setStatus("DELAYED 40")
  F->>B: onStatusChanged(this)
  F->>S: onStatusChanged(this)
  F->>C: onStatusChanged(this)
  Note over B,C: each asks the flight for code() and status()
```

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

```java
// 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.

## 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:

```java
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*.)

```mermaid {alt="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." caption="Closed, but still on the list: 1,004 listeners instead of 4."}
flowchart LR
  F["Flight.setStatus()"] --> L["listeners: 1,004"]
  L --> A["board · SMS · crew · loyalty<br/>(4 live)"]
  L --> D["1,000 closed trackers<br/>(still referenced)"]
  class F c6
  class A good
  class D bad
```

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.

```java
    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:

```java
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:

```java
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:

```java
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.

```mermaid {alt="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." caption="PropertyChangeSupport keeps the list and pushes name, old value and new value."}
sequenceDiagram
  participant S as Settings
  participant P as support
  participant W as repaint
  participant R as save
  Note over S: setTheme("dark")
  S->>P: fire: theme, light → dark
  P->>W: propertyChange(e)
  P->>R: propertyChange(e)
  Note over S: setTheme("dark") again
  S->>P: fire: theme, dark → dark
  Note over P: equal: no event
```

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.

```mermaid {alt="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." caption="Observer keeps the list. Publish subscribe hands it to a broker."}
flowchart TB
  subgraph obs["Observer"]
    direction TB
    F1["Flight<br/>(keeps the list)"] --> O1["DepartureBoard"]
    F1 --> O2["PassengerSms"]
    F1 --> O3["CrewRoster"]
  end
  subgraph ps["Publish-subscribe"]
    direction TB
    F2["Flight"] -->|publish| BR["broker<br/>topic: flights"]
    BR --> S1["service A"]
    BR --> S2["service B"]
    BR --> S3["service C"]
  end
  obs ~~~ ps
  class F1,F2 c6
  class BR hl
```

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

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

```mermaid {alt="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." caption="When Observer pays for itself."}
flowchart TD
  A{"How many parties<br/>need to know?"} -->|one, fixed| D["call it directly"]
  A -->|several, or unknown| B{"Must they run<br/>in a set order?"}
  B -->|yes| Q["write a sequence"]
  B -->|no| C{"Must delivery survive<br/>a crash or cross services?"}
  C -->|yes| P["use a broker<br/>(publish-subscribe)"]
  C -->|no| O["Observer<br/>(watch for cascades)"]
  class D,Q,P muted
  class O good
```

## 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**.

```mermaid {alt="Recap chain: a list behind one interface, observers subscribe from outside, announce each change to the list, every subscribe needs an unsubscribe." caption="The flight never learned a single name."}
flowchart LR
  A["a list behind<br/>one interface"] --> B["observers subscribe<br/>from outside"] --> C["announce to the list<br/>(push or pull)"] --> D["sign up,<br/>sign off"]
  class A c1
  class D good
```

> **Know the list, not the listeners.**

Related patterns: the [Decorator pattern](/patterns/decorator-pattern/) also works through one
shared interface, but wraps a single object instead of broadcasting to many; the
[Strategy pattern](/patterns/strategy-pattern/) plugs in one interchangeable algorithm; the
[Command pattern](/patterns/command-pattern/) turns a call into an object you can queue or
undo; and in a [Chain of Responsibility](/patterns/chain-of-responsibility-pattern/) one
handler takes the request, while in Observer every listener hears it.
