Observer Pattern Guide

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

Key Components

Subject

  • Maintains observer list
  • Provides subscription methods
  • Notifies observers of updates

Observer

  • Registers with subject
  • Defines update method
  • Receives state changes

Implementation Example

Subject Class

// Observer subject
class Subject {
  constructor() { this.observers = [] }

  subscribe(observer) {
    this.observers = [...this.observers, observer];
  }

  notify(data) {
    this.observers.forEach(obs => obs.update(data));
  }
}
                

Observer Class

// Observer implementation
class Observer {
  update(data) {
    console.log(`Received update: ${data}`);
  }
}
                

Common Use Cases

Real-time UI

Components update reactively when data changes

Data Synchronization

Objects react to changes in data models

Event Handling

Event listeners in GUI frameworks

Notification Systems

User notifications and alerts

Frequently Asked Questions

How to detect changes?

Why use this pattern?