Course contentsShow
← Computer Science
Lesson 2289 of 2,87251. Design PatternsFree lesson

Observer Pattern Fundamentals

Establishing one-to-many dependencies where observers are notified automatically when subject state changes.

Observer Pattern Fundamentals

What you'll learn: How to automatically notify multiple dependent objects when one object's state changes.

The Core Problem

Imagine you're building a weather station app. When the temperature changes, you need to update the display widget, send notifications to subscribed users, and log the data — all automatically. Hard-coding these updates creates tight coupling and makes your code fragile.

The Observer Pattern solves this by establishing a one-to-many dependency between objects. One object (the subject or observable) maintains a list of dependents (the observers) and notifies them automatically when its state changes.

How It Works

Think of it like a magazine subscription service:

  • The subject is the publisher that holds the data
  • Observers are subscribers who want updates
  • When the magazine (subject state) is ready, all subscribers get notified automatically
  • Subscribers can join or leave the mailing list at any time

The subject doesn't need to know what the observers do with the information — it just notifies them. This decouples the subject from its observers.

Key Components

  1. Subject: Maintains observer list, provides methods to attach/detach observers, notifies all observers on state change
  2. Observer: Defines an update interface that subjects use for notification
  3. Concrete Subject: Stores state, sends notifications when state changes
  4. Concrete Observers: Implement the update interface, maintain reference to subject (if needed)

This pattern is everywhere: GUI event systems, model-view architectures (MVC), real-time data feeds, and pub-sub messaging systems all use observer-like mechanisms.

Key Takeaway: The Observer Pattern enables loose coupling by letting subjects notify multiple observers automatically when state changes, without knowing what those observers actually do with the updates.