Design Patterns

Pattern 18 of 23, Behavioral family

Observer

Also known as: Publish-Subscribe

Define a subscription mechanism to automatically notify several objects of a state change.

The problem

When an order is paid, you need to send an email, decrement the stock, track analytics… Coding these calls inside Order couples it to all of those services.

The solution

The subject keeps a list of subscribers and notifies them when its state changes. Observers subscribe / unsubscribe themselves, without the subject knowing their class.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. Observers subscribe to the subject.
  2. StockListener → Order [NEW]: subscribe()
  3. The subject's state changes…
  4. …it notifies each subscriber, without knowing its class.
  5. Order [PAID] → StockListener: update(order)
  6. New subscriber added without modifying Order (Open/Closed).

An analogy

Subscribing to a YouTube channel: you get notified of every new video, and you can unsubscribe at any time.

When to use it

  • Domain events (OrderPaid…)
  • Reactive UI, data binding, stores (Redux, signals)
  • Webhooks, pub/sub, WebSockets

Pros and cons

Pros

  • Open/Closed: new subscribers without touching the subject
  • Dynamic relationships at runtime
  • Loose coupling

Cons

  • Notification order is not guaranteed
  • Memory leaks if you forget to unsubscribe
  • Notification cascades are hard to follow

Implementations

The same example, written idiomatically in each language.

Observer in Python

observer.py 23 lines
from collections import defaultdict
from typing import Callable, Any


class EventBus:
    def __init__(self):
        self._subs: dict[str, list[Callable[[Any], None]]] = defaultdict(list)

    def subscribe(self, event: str, fn: Callable[[Any], None]):
        self._subs[event].append(fn)
        return lambda: self._subs[event].remove(fn)    # unsubscribe function

    def emit(self, event: str, payload: Any):
        for fn in list(self._subs[event]):
            fn(payload)


bus = EventBus()
bus.subscribe("order.paid", lambda o: print("Email to", o["email"]))
unsubscribe = bus.subscribe("order.paid", lambda o: print("Stock -", o["qty"]))

bus.emit("order.paid", {"email": "client@mail.tn", "qty": 2})
unsubscribe()

Observer in TypeScript

observer.ts 22 lines
type Listener<T> = (payload: T) => void;

class Subject<T> {
  private listeners = new Set<Listener<T>>();

  subscribe(fn: Listener<T>) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn); // unsubscribe
  }

  notify(payload: T) {
    this.listeners.forEach((fn) => fn(payload));
  }
}

const orderPaid = new Subject<{ id: number; email: string }>();

const off = orderPaid.subscribe((o) => sendEmail(o.email));
orderPaid.subscribe((o) => updateStock(o.id));

orderPaid.notify({ id: 1, email: "client@mail.tn" });
off();

Observer in Java

observer.java 18 lines
interface OrderListener { void onPaid(Order order); }

class Order {
    private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
    private String status = "NEW";

    void subscribe(OrderListener l)   { listeners.add(l); }
    void unsubscribe(OrderListener l) { listeners.remove(l); }

    void markPaid() {
        status = "PAID";
        listeners.forEach(l -> l.onPaid(this));
    }
}

order.subscribe(o -> mailer.sendReceipt(o));
order.subscribe(o -> stock.decrement(o));
order.markPaid();

Observer in C#

observer.cs 19 lines
public record OrderPaidEventArgs(int OrderId);

public class Order
{
    public int Id { get; init; }
    public string Status { get; private set; } = "NEW";

    public event EventHandler<OrderPaidEventArgs>? Paid;   // observer built into C#

    public void MarkPaid()
    {
        Status = "PAID";
        Paid?.Invoke(this, new OrderPaidEventArgs(Id));
    }
}

order.Paid += (_, e) => mailer.SendReceipt(e.OrderId);
order.Paid += (_, e) => stock.Decrement(e.OrderId);
order.MarkPaid();

Observer in PHP

observer.php 30 lines
final class Order implements SplSubject
{
    private SplObjectStorage $observers;
    public string $status = 'NEW';

    public function __construct() { $this->observers = new SplObjectStorage(); }

    public function attach(SplObserver $o): void { $this->observers->attach($o); }
    public function detach(SplObserver $o): void { $this->observers->detach($o); }

    public function notify(): void
    {
        foreach ($this->observers as $o) {
            $o->update($this);
        }
    }

    public function markPaid(): void
    {
        $this->status = 'PAID';
        $this->notify();
    }
}

final class EmailListener implements SplObserver
{
    public function update(SplSubject $order): void { /* send the receipt */ }
}

// Laravel: event(new OrderPaid($order)) + Listeners, or Model Observers

Observer in Go

observer.go 29 lines
type Event struct{ OrderID int }

type Bus struct {
    mu   sync.RWMutex
    subs []chan Event
}

func (b *Bus) Subscribe() <-chan Event {
    ch := make(chan Event, 8)
    b.mu.Lock()
    b.subs = append(b.subs, ch)
    b.mu.Unlock()
    return ch
}

func (b *Bus) Publish(e Event) {
    b.mu.RLock()
    defer b.mu.RUnlock()
    for _, ch := range b.subs {
        ch <- e
    }
}

emails := bus.Subscribe()
go func() {
    for e := range emails {
        sendReceipt(e.OrderID)
    }
}()

Frequently asked questions

What is the Observer design pattern?

Define a subscription mechanism to automatically notify several objects of a state change. The subject keeps a list of subscribers and notifies them when its state changes. Observers subscribe / unsubscribe themselves, without the subject knowing their class.

When should you use the Observer pattern?

Domain events (OrderPaid…); Reactive UI, data binding, stores (Redux, signals); Webhooks, pub/sub, WebSockets.

What are the pros and cons of the Observer pattern?

Pros: Open/Closed: new subscribers without touching the subject; Dynamic relationships at runtime; Loose coupling. Cons: Notification order is not guaranteed; Memory leaks if you forget to unsubscribe; Notification cascades are hard to follow.