Sitemap

Observer Pattern

12 min readJul 20, 2026

--

Imagine you’re asked to build a Weather Monitoring application.

There’s a WeatherData object connected to physical sensors. It knows three things at any moment:

  • current temperature
  • current humidity
  • current pressure

Whenever the sensors detect new readings, WeatherData is notified through a method called measurementsChanged().

Now, the app also needs to show this data on multiple screens:

  • a Current Conditions Display (shows the live numbers)
  • a Statistics Display (shows min/max/average)
  • a Forecast Display (predicts tomorrow’s weather)

So every time the measurements change, all three displays need to update themselves with the new data.

How most people first implement this

The natural first instinct is: “Easy — whenever measurements change, just call update() on every display, one by one."

public class WeatherData {

private float temperature;
private float humidity;
private float pressure;

private CurrentConditionsDisplay currentConditionsDisplay;
private StatisticsDisplay statisticsDisplay;
private ForecastDisplay forecastDisplay;

public void measurementsChanged() {
float temp = getTemperature();
float humidity = getHumidity();
float pressure = getPressure();

currentConditionsDisplay.update(temp, humidity, pressure);
statisticsDisplay.update(temp, humidity, pressure);
forecastDisplay.update(temp, humidity, pressure);
}

public float getTemperature() { return temperature; }
public float getHumidity() { return humidity; }
public float getPressure() { return pressure; }
}

It compiles. It works. It shows the right numbers on all three screens. So — what’s actually wrong with it?

What’s Wrong With This?

Let’s think about what happens as this app grows.

  1. WeatherData is coding directly against concrete classes. It literally knows the names CurrentConditionsDisplay, StatisticsDisplay, ForecastDisplay. If tomorrow the product team wants a new Mobile App Display, you have to open up WeatherData and add a fourth line by hand.
  2. You can’t add or remove displays at runtime. The list of displays is hardcoded inside measurementsChanged(). What if a user wants to turn the Statistics Display off? There's no clean way to do that without editing this method.
  3. WeatherData is doing too much. It's supposed to be the thing that holds weather data — instead it's also become the thing responsible for knowing every single display that exists and manually pushing data to each one. Every future display change means touching this one already-working class again.
  4. This should feel familiar. This is the exact same problem we saw with the Vehicle class before we applied Strategy — one part of the code (which displays exist, and how many) is tightly welded to a part that should stay stable (how weather data gets collected). We already know from Design Principle 1: identify what varies, and separate it from what stays the same. The set of displays varies. WeatherData's job of tracking measurements stays the same. Right now, they're tangled together.

What we actually need is a way for WeatherData to say: "My data changed — anyone who cares can come and get it," without needing to know who's listening, how many are listening, or calling each one by name.

That’s exactly what the Observer Pattern gives us.

What Is the Observer Pattern?

Think about how a newspaper subscription works in real life:

  • The publisher (the newspaper company) prints new editions.
  • Subscribers sign up once to receive the newspaper.
  • Every time a new edition comes out, it’s delivered automatically to every subscriber — the publisher doesn’t personally know each subscriber’s life, it just delivers to whoever is on the subscriber list.
  • A subscriber can unsubscribe anytime, and new people can subscribe anytime — without the newspaper company changing how it prints the news.

This is the Publisher–Subscriber relationship, and it’s precisely the Observer Pattern:

  • WeatherData becomes the Publisher (also called the Subject).
  • CurrentConditionsDisplay, StatisticsDisplay, ForecastDisplay become Subscribers (also called Observers).
  • The Subject keeps a list of Observers — it doesn’t know their concrete class, only that each one can be notified.
  • Any Observer can subscribe (register) or unsubscribe (remove itself) at any time, without the Subject’s core logic ever changing.

The formal definition

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

Breaking that down:

  • “one-to-many dependency” → one WeatherData object, many display objects depending on it.
  • “when one object changes state” → when temperature/humidity/pressure changes.
  • “all of its dependents are notified and updated automatically” → every subscribed display gets the new data without WeatherData having to know their concrete class or call them out by name.
Press enter or click to view image in full size

Four pieces, each with one job:

  • Subject (interface) — the contract any "publisher" must follow. Just three methods: a way to register an observer, a way to remove one, and a way to notify all of them. It says nothing about how state is stored or what the state even is.
  • Observer (interface) — the contract any "subscriber" must follow. Just one method: update(), called whenever the subject's state changes. It says nothing about what the observer does with that update.
  • ConcreteSubject — an actual class that implements Subject. This is where the real state lives (getState() / setState()), and it's the one that keeps the actual list of registered observers and calls notifyObservers() when its state changes.
  • ConcreteObserver — any class that implements Observer. It holds a reference back to the subject it's registered with (so it can, for instance, pull state or unregister itself), and defines its own update() logic — however it wants to react to the change.

Notice the two dotted arrows in the diagram (implements) versus the two solid arrows (observers, subject) — that distinction is the whole point of this pattern, and it's worth sitting with.

The Power of Loose Coupling

When two objects are loosely coupled, they can talk to each other and work together — but each one knows very little about the other. Neither one needs to understand the other’s internal details, its concrete class, or how it does its job.

This might sound like a small thing, but it’s actually where most of the flexibility in good software design comes from. And the Observer Pattern is a textbook example of it in action. Let’s go through exactly how it pulls this off.

1. The Subject only knows that an Observer implements the Observer interface — nothing more. It doesn't know the observer's class name. It doesn't know what the observer does with the update, or how it does it. All it knows is: "this object has an update() method I can call." That's it.

2. New observers can be added at any time. Since the Subject only depends on a list of objects implementing Observer, you can register a brand-new observer whenever you want — even while the program is running. You can also swap one observer for another at runtime, or remove one entirely, and the Subject just keeps working, completely unaffected.

3. The Subject never needs to change to support a new type of observer. Say a brand-new class shows up tomorrow that needs to start receiving updates. You don’t touch the Subject’s code at all. You just make that new class implement Observer and register it. The Subject doesn't care who or what it is — it will notify any object that implements the interface.

4. Subjects and Observers can be reused on their own, independently of each other. Because they aren’t tightly stitched together, you can take a Subject and use it in a different context with a completely different set of observers — or take an Observer and attach it to a different subject. Neither one drags the other along as baggage.

5. Changes to one side don’t break the other. As long as the Subject still honors the Subject interface, and the Observer still honors the Observer interface, you're free to change how either of them works internally — rewrite the logic, change the data structures, anything — without the other one even noticing.

Take a moment and count how many different kinds of change this design absorbs without breaking a sweat: new observer types, removed observers, runtime swaps, reused subjects, reused observers, internal rewrites on either side. None of these require touching the other object. That’s the real payoff of loose coupling.

Design Principle

Strive for loosely coupled designs between objects that interact.

Loosely coupled objects reduce the ripple effect of change — when one object changes, the fewer other objects it depends on tightly, the fewer things break, and the easier the whole system is to extend. The Observer Pattern isn’t just an example of this principle — it’s basically a direct, reusable implementation of it.

How to Think Through the Implementation

Map that sentence onto the Weather Station:

  • The “one” → WeatherData. It has state (temperature, humidity, pressure), and that state changes.
  • The “many” → the display elements (CurrentConditionsDisplay, StatisticsDisplay, ForecastDisplay). They depend on that state to do their job.
  • “Notified and updated automatically” → whenever the measurements change, every registered display should get the new values without WeatherData having to know their class names.

Once you frame it that way, a few design questions naturally fall out. Answering them, in order, is basically the whole implementation:

Get Krutish Raval’s stories in your inbox

Join Medium for free to get updates from this writer.

1. How does a display let WeatherData know it wants updates? It has to register itself. So WeatherData needs a way to accept new observers into a list, and a way to remove them later.

2. How does WeatherData send the data, if it doesn’t know the display’s concrete type? This is the key trick of the pattern: it doesn’t call CurrentConditionsDisplay's methods directly. Instead, every display agrees to implement one common method — say, update(). WeatherData only ever talks to that method, through a shared Observer interface. It doesn't need to know or care what's on the other side of that interface.

3. What should that shared contract look like? This gives you the two interfaces before you write any concrete class:

  • Subject — the contract for anything that broadcasts changes: register an observer, remove an observer, notify all observers.
  • Observer — the contract for anything that wants to be notified: just one method, update().

4. Who implements what?

  • WeatherData implements Subject, because it's the thing broadcasting changes.
  • Each display implements Observer, because each one wants to receive changes.

5. How does the flow actually run end to end?

  1. Each display is created and registers itself with WeatherData in its constructor.
  2. Sensors update WeatherData with new readings.
  3. WeatherData calls notifyObservers().
  4. That method loops through every registered observer and calls update() on each, passing the new data.
  5. Each display’s own update() decides what to do with that data — show it, average it, use it to predict tomorrow, whatever.

Notice that at no point does WeatherData say currentConditionsDisplay.update(...) by name. It only ever says "for every observer in my list, call update()." That one shift is what removes the hardcoding we complained about earlier.

With that mental model in place, the code below should feel like it’s writing itself rather than something to memorize.

Class Diagram

Press enter or click to view image in full size

The Implementation

Step 1: Define the interfaces

public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}

public interface Observer {
public void update(float temp, float humidity, float pressure);
}

public interface DisplayElement {
public void display();
}

What’s going on here:

  • Subject is the contract for anything that publishes changes. It doesn't say how state is stored — just that observers can register, unregister, and be notified.
  • Observer is the contract for anything that listens. It only has update(). We're passing temp, humidity, and pressure directly as arguments here — a simple "push" style, where the subject hands over the data itself.
  • DisplayElement is separate from Observer on purpose. Being an observer (something that listens for weather changes) and being displayable (something that can show itself on screen) are two different responsibilities. Not every observer necessarily needs to be shown on screen, so we keep this as its own small interface.

Step 2: Make WeatherData the Concrete Subject

public class WeatherData implements Subject {
private List<Observer> observers;
private float temperature;
private float humidity;
private float pressure;

public WeatherData() {
observers = new ArrayList<Observer>();
}

public void registerObserver(Observer o) {
observers.add(o);
}

public void removeObserver(Observer o) {
observers.remove(o);
}

public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature, humidity, pressure);
}
}

public void measurementsChanged() {
notifyObservers();
}

public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
}

What’s going on here:

  • observers is just a list. It doesn't know or care what kinds of objects are in it, only that each one is an Observer.
  • registerObserver() and removeObserver() are exactly what they sound like — add to or remove from that list. This is what lets displays come and go at runtime.
  • notifyObservers() is the heart of the pattern: loop over the list, call update() on each one. This is the piece that replaces the old hardcoded block of currentConditionsDisplay.update(...), statisticsDisplay.update(...), forecastDisplay.update(...).
  • setMeasurements() simulates new sensor data coming in. It updates the state, then calls measurementsChanged(), which triggers the notification.

Notice WeatherData no longer mentions CurrentConditionsDisplay or any other concrete display anywhere in this file. That coupling is gone.

Step 3: Make a Concrete Observer

public class CurrentConditionsDisplay implements Observer, DisplayElement {
private float temperature;
private float humidity;
private WeatherData weatherData;

public CurrentConditionsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}

public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}

public void display() {
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}

What’s going on here:

  • It implements Observer, because it needs an update() method WeatherData can call. It implements DisplayElement, because it also needs a display() method, separate from the update logic.
  • The constructor is handed the WeatherData object and immediately calls weatherData.registerObserver(this). This is the self-registration step — the display signs itself up rather than WeatherData reaching out to find it.
  • update() just stores the new values and calls display(). This is where the "push" data from notifyObservers() lands.
  • display() does whatever this particular display is meant to do — here, just printing to the console. A StatisticsDisplay would instead keep running min/max/average totals, and a ForecastDisplay would use the pressure trend to guess tomorrow's weather. Each display decides that for itself; WeatherData never needs to know the difference.

Step 4: Wire it together

public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();

CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);

weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}

Each call to setMeasurements() simulates a new sensor reading. Internally it triggers measurementsChanged() → notifyObservers() → every registered display's update(), in that order — automatically, without WeatherData ever naming a single display class.

That’s the payoff of thinking it through interface-first: register, notify, update. Three verbs, and the whole pattern falls out of them.

The Observer Pattern in the Wild

Once you know what to look for, you’ll spot the Observer Pattern all over the place — you don’t have to build it yourself every time to benefit from it.

Take Java’s Swing library, the toolkit used to build desktop UIs. Every basic component, like a JButton, lets you attach and detach listeners for events that happen on it — a button press, for instance. In Swing, "listener" is just another name for "observer." Under the hood, the button is the subject, and every listener attached to it is an observer waiting to be notified when something happens.

This isn’t only a Java thing either. JavaScript’s event system, Cocoa and Swift’s Key-Value Observing, and libraries like RxJava all lean on the same basic idea: something changes, and anything that registered interest gets told about it automatically.

A tiny example: the “Should I do it?” button

Here’s a small Swing app to make this concrete. There’s one button that says “Should I do it?” and two listeners attached to it — an AngelListener and a DevilListener. Every time the button is clicked, both listeners get notified and each prints its own opinion.

public class SwingObserverExample {
JFrame frame;

public static void main(String[] args) {
SwingObserverExample example = new SwingObserverExample();
example.go();
}

public void go() {
frame = new JFrame();

JButton button = new JButton("Should I do it?");
button.addActionListener(new AngelListener());
button.addActionListener(new DevilListener());

// Set frame properties here
}

class AngelListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Don't do it, you might regret it!");
}
}

class DevilListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Come on, do it!");
}
}
}

What’s going on here:

  • button is the subject. addActionListener() is exactly like our registerObserver() — it adds an observer to the button's internal list.
  • AngelListener and DevilListener are the observers. Instead of implementing an Observer interface with an update() method, Swing has them implement ActionListener with an actionPerformed() method — same idea, different name.
  • When the button is clicked, Swing itself plays the role of notifyObservers(): it loops through every listener attached to that button and calls actionPerformed() on each one, in the order they were added.
  • Neither listener knows the other exists. The button doesn’t know or care what AngelListener and DevilListener actually do — it only knows both implement ActionListener. Click the button, and you get both opinions, one after another:

Come on, do it!
Don’t do it, you might regret it!

That’s the entire pattern, just wearing different names: addActionListener() instead of registerObserver(), ActionListener instead of Observer, actionPerformed() instead of update(). Once you recognize the shape of it, you'll start noticing it everywhere.

--

--

Krutish Raval
Krutish Raval

Written by Krutish Raval

Software engineer with a soft spot for hard problems — backend systems, infrastructure, and the occasional deep dive into how systems really work.