Behavioral

Observer

Defines a subscription mechanism to notify multiple objects about events.

Event systemsUI updatesPub/sub messaging

Understanding Observer

The Observer pattern establishes a one-to-many dependency between objects — when one object (the subject) changes state, all dependent objects (observers) are automatically notified and updated. Also known as Pub/Sub, this pattern is the backbone of event-driven architecture. In Go, the subject maintains a slice of observers implementing a common interface, and calls their update methods whenever state changes. This decouples the event producer from consumers, allowing new observers to be added without modifying the subject.

Key Concepts

  • Subject (Publisher) — maintains state and a list of registered observers, notifying them on state changes
  • Observer (Subscriber) — implements an update interface to receive notifications from the subject
  • Loose coupling — the subject only knows the observer interface, not the concrete observer types
  • Push vs. Pull — subject can push data to observers, or observers can pull what they need from the subject

When to Use

✅ Use when
  • • A change to one object requires updating others, and you don\'t know how many
  • • You\'re building an event system, message bus, or reactive UI
  • • Objects need to be notified without tight coupling to the notifier
  • • The set of listeners changes dynamically at runtime
⚠️ Avoid when
  • • The dependency is simple 1-to-1 — a direct callback is clearer
  • • Notification order matters and is hard to guarantee
  • • Observers modify the subject during notification, causing cascading updates

Structure

Subject (state + observers[])
↓ Notify()
<<Observer Interface>>
↓ implements
ObserverA
ObserverB
ObserverC

How It Works

Subject
Publisher
state: "old"
Observers
Observer A
Observer B
Observer C
Subject holds state
1

Subject

Subject maintains state and list of observers.

1 / 4

Basic Implementation

Simple subject with multiple observers:

main.go
Loading editor...

Real-World Example: Stock Market

Stock price notifications with traders and alert bots:

main.go
Loading editor...