Observer Pattern

Let any number of objects react when one object changes, without that object knowing who they are.

Overview

The Observer pattern is one of the behavioral patterns in Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994). One object, the subject, holds some state that others care about. Instead of the subject calling each of them by name, the interested objects, the observers, register with the subject, and the subject tells all of them whenever its state changes. The subject knows only that each observer has an update method. It does not know what they do with the news.

Every event system is this pattern: a button that runs handlers when clicked, a data model that repaints views, a price feed that triggers alerts. Interviewers ask about Observer to see whether you can decouple a change from its effects, and whether you know the three classic failures: observers that are never removed and leak memory, observers that change the subject and cause loops, and notifications whose order or timing surprises people.

The problem it solves

A thermostat reads a temperature. A display shows it, an alarm checks it, a log records it. If the thermostat calls all three directly, it must import all three, and adding a fourth means editing the thermostat. Worse, the thermostat cannot be reused anywhere the display does not exist.

Observer turns those direct calls around. With direct calls, the subject imports and calls every dependent, adding a dependent means editing the subject, and the dependents exist for the subject's whole lifetime. The code is easy to read but tightly coupled. With Observer, the subject holds a list of observers and calls update on each, adding a dependent means calling attach, and dependents come and go at run time. The code is loosely coupled but harder to trace.

Interview questions

  • What is the lapsed listener problem, and how do you prevent it?
  • What goes wrong when an observer modifies the subject during a notification, and how do you guard against it?
  • How is Observer different from publish-subscribe?
  • Should a subject notify observers synchronously or asynchronously?
  • How does reactive programming extend the Observer pattern?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio