Observer

Category

Behavioral pattern

Problem

Define a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically.

Solution

  • The Subject maintains a list of Observers and provides methods to attach/detach them
  • When the Subject’s state changes, it notifies all attached Observers
  • Observers implement an update interface to receive notifications

Structure

  • Subject: Maintains a list of observers; notifies them of state changes
  • Observer: Defines an update interface for objects that should be notified
  • ConcreteSubject: Stores state; sends notifications when state changes
  • ConcreteObserver: Implements the update interface; maintains a reference to the subject

Key Benefits

  • Loose coupling — Subject and Observers are decoupled; Subject doesn’t know concrete observer types
  • Broadcast communication — One change can notify many observers
  • Dynamic relationships — Observers can be added/removed at runtime

Trade-offs

  • Notification order — No guaranteed order of observer notifications
  • Unexpected updates — Observers may be notified of changes they don’t care about

When to Use

  • A change to one object requires changing others, and you don’t know how many objects need to be changed
  • An object should be able to notify other objects without making assumptions about who they are
  • You need a publish-subscribe mechanism

Examples