design patterns · behavioral

Observer

Defines a one-to-many dependency so when one object changes state, all its dependents are notified automatically.

easybehavioral0.5h
Ask GPTConfidence

Pattern

Overview

Intent

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

Real-World Analogy

YouTube subscription - you subscribe to a channel; when a new video is published, all subscribers receive a notification automatically.

When multiple objects need to react to changes in one object, hardcoding their relationships creates tight coupling. Observer lets the subject maintain a list of observers and notify them automatically on state change.

Subject maintains a list of Observers. subscribe() adds, unsubscribe() removes. When state changes, the subject calls update() on all registered observers. Observers react independently.

When to use

Event systems, GUI event listeners, MVC (model notifies views), real-time data feeds (stock prices, weather), reactive programming foundations.

When not to

When notification order matters and must be guaranteed. When observers are always the same set - direct method calls are clearer.

Participants

SubjectConcreteSubjectObserverConcreteObserver

Key Insights

  • Java's java.util.Observable and EventListener are built-in Observer implementations
  • Weak references for observers prevent memory leaks when observers are garbage-collected
  • The push model (subject sends data in update()) vs pull model (observer queries subject) are two variants
  • RxJava, ReactiveX, and Node.js EventEmitter all implement Observer