teacher
Sign in

Observer

Let many listeners subscribe to one source and be told when it changes, without the source knowing who they are.

22 min3 interactive

The problem it solves

A price changes. Several things care: a log, an alert, a chart, a trading rule. The naive design makes the price class call each of them by name:

void setPrice(int p) { logger.log(p); alert.check(p); chart.redraw(p); }

Costs of that:

  • The price class must know every dependant, so adding one means editing it.
  • It cannot be reused somewhere that has no chart.
  • Removing a dependant at run time is awkward.

Observer reverses the dependency. The source (called the subject) keeps a list of listeners that implement one small interface. When something happens it walks the list and calls each one. The subject knows only the interface, never the concrete listeners.

You know this as events: button clicks, addEventListener, a notification bell. Message brokers such as Kafka are the same idea across machines (publish-subscribe, or pub-sub).

1 of 7