Observer Command

Observer + Command (GoF Behavioral)

Observer: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." Command: "Encapsulate a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations." — GoF


The common theme — a loose link between sender and receiver

Both patterns decouple the one who triggers the action from the one who performs it:

This lets you add new behaviour without changing the sender — OCP in action.


Observer

Canonical form

from typing import Callable


class EventBus:
    """Pythonic Observer — listeners are Callable."""

    def __init__(self):
        self._listeners: dict[str, list[Callable]] = {}

    def subscribe(self, event_type: str, listener: Callable) -> None:
        self._listeners.setdefault(event_type, []).append(listener)

    def unsubscribe(self, event_type: str, listener: Callable) -> None:
        if event_type in self._listeners:
            self._listeners[event_type].remove(listener)

    def publish(self, event_type: str, payload: dict) -> None:
        for listener in self._listeners.get(event_type, []):
            listener(payload)

Usage:

bus = EventBus()

# Subscribers:
bus.subscribe("order_created", lambda e: print(f"email: {e['id']}"))
bus.subscribe("order_created", lambda e: print(f"metrics: {e['total']}"))
bus.subscribe("order_created", lambda e: print(f"audit: {e}"))

# Sender — does not know who is subscribed:
bus.publish("order_created", {"id": 42, "total": 100.0})
# email: 42
# metrics: 100.0
# audit: {...}

Key signs of Observer:

  1. Subject (EventBus or Subject) keeps a list of subscribers.
  2. Subscribe / unsubscribe — subscribers can be added or removed at runtime.
  3. Publish — notifies all subscribers.
  4. Sender does not know whom — fully decoupled.

Two styles — push vs pull

Push (more common)

The subject pushes data to the subscriber:

bus.publish("order_created", {"id": 42, "total": 100.0})

The listener receives ready data.

Pull

The subject notifies of the fact of change. The listener fetches by itself:

bus.publish("order_changed", order_id=42)

def on_changed(order_id):
    order = order_repository.get(order_id)        # the listener pulls

Push is simpler, but the listener receives all the data (even what it does not need). Pull is more flexible, but the listener knows how to fetch the data (more coupling).

Modern Python is mostly push with small events.


Pythonic variants of Observer

1. Just a list[Callable] (minimalist)

class Order:
    def __init__(self):
        self._on_created: list[Callable[["Order"], None]] = []

    def on_created(self, callback):
        self._on_created.append(callback)

    def create(self):
        # ... creation logic ...
        for cb in self._on_created:
            cb(self)

No EventBus class — fine for one source of events.

2. The blinker or pyee library

from blinker import signal

order_created = signal("order_created")

@order_created.connect
def send_email(sender, **kwargs):
    print(f"email: {kwargs}")

order_created.send(None, order_id=42)

A ready-made implementation, no hand-rolled EventBus.

3. Decorator-style subscriptions

bus = EventBus()

@bus.on("order_created")
def send_email(event):
    print(f"email: {event}")

Syntactic sugar on top of subscribe().


Classic Observer examples

Domain Subject Observers
GUI Button onClick listeners
Game Entity Health watchers, Animation, Sound
Web OrderService EmailSender, AnalyticsTracker, AuditLogger
Pub/Sub Topic Consumers (Kafka, RabbitMQ)
Reactive Observable Subscribers (RxPy)
Cache invalidation Repository CacheProxy.invalidate

Observer anti-patterns

1. Listeners with side effects that depend on each other

bus.subscribe("user_created", create_account)        # creates an account
bus.subscribe("user_created", send_welcome_email)    # ← needs the account to exist!

The execution order is implicit. If someone adds a third listener, the order may break. Anti-pattern.

Fix: do not rely on listener order. If there is a sequence, it is a procedure, not an Observer.

2. Heavy listeners block publish

bus.subscribe("order_created", expensive_synchronous_operation)
bus.publish("order_created", ...)                    # blocks for a long time

Observer is synchronous by default. For long operations, use async or a task queue (Celery, RQ).

3. Stale listeners (memory leak)

class Widget:
    def __init__(self, bus):
        bus.subscribe("click", self.on_click)

widget = Widget(bus)
del widget                                            # ← the bus still holds self.on_click!

The bus holds a strong reference to the listener, so the widget is not collected. A classic memory leak.

Fix: use weakref for listeners, or explicit unsubscribe().


Command

Canonical form

from typing import Protocol


class Command(Protocol):
    def execute(self) -> None: ...
    def undo(self) -> None: ...


class AddToCart:                                      # ← concrete command
    def __init__(self, cart: list, item: str):
        self._cart = cart
        self._item = item

    def execute(self) -> None:
        self._cart.append(self._item)

    def undo(self) -> None:
        self._cart.remove(self._item)


class RemoveFromCart:
    def __init__(self, cart: list, item: str):
        self._cart = cart
        self._item = item
        self._index: int | None = None

    def execute(self) -> None:
        self._index = self._cart.index(self._item)
        self._cart.remove(self._item)

    def undo(self) -> None:
        if self._index is not None:
            self._cart.insert(self._index, self._item)

An invoker with history:

class CommandHistory:
    def __init__(self):
        self._history: list[Command] = []

    def execute(self, cmd: Command) -> None:
        cmd.execute()
        self._history.append(cmd)

    def undo_last(self) -> None:
        if not self._history:
            return
        cmd = self._history.pop()
        cmd.undo()

Usage:

cart = []
history = CommandHistory()

history.execute(AddToCart(cart, "milk"))
history.execute(AddToCart(cart, "bread"))
print(cart)                                           # ["milk", "bread"]

history.undo_last()                                   # removes bread
print(cart)                                           # ["milk"]

history.undo_last()                                   # removes milk
print(cart)                                           # []

Key signs of Command:

  1. The request is an object with an execute() method (and optionally undo()).
  2. The Invoker (CommandHistory) does not know what the command does, it only calls execute().
  3. The command holds all the data needed for execution (cart, item).
  4. undo() is the inverse operation — for that you often need to store the state before.

Why Command is powerful

1. Undo / Redo

Any text editor, any graphical editor.

2. Queue / defer

queue: list[Command] = []
queue.append(SendEmail(...))
queue.append(GenerateReport(...))

# Run later (at night, on a worker):
for cmd in queue:
    cmd.execute()

3. Logging / audit trail

class LoggingHistory:
    def execute(self, cmd):
        log.info(f"executing {cmd}")
        cmd.execute()
        log.info(f"executed {cmd}")

Every operation is a recorded object. You can replay the journal on another database.

4. Macros / composite commands

class Macro:                                          # ← also a Command!
    def __init__(self, commands: list[Command]):
        self._commands = commands

    def execute(self):
        for c in self._commands:
            c.execute()

    def undo(self):
        for c in reversed(self._commands):
            c.undo()

Composition of Commands is the same Composite Pattern.

5. Transactions

class TransactionalHistory:
    def execute_batch(self, commands: list[Command]):
        executed: list[Command] = []
        try:
            for c in commands:
                c.execute()
                executed.append(c)
        except Exception:
            for c in reversed(executed):
                c.undo()                              # rollback
            raise

Pythonic Command — often just a Callable

For simple commands without undo, a plain function or lambda is enough:

queue: list[Callable[[], None]] = []
queue.append(lambda: print("hi"))
queue.append(lambda: print("hello"))

for cmd in queue:
    cmd()

Callable[[], None] is the minimal Command pattern in Python. Classes are only needed when:


Command anti-patterns

1. A Command class with no good reason

class ProcessOrder:
    def execute(self): ...
    # no undo

If you do not need undo, in Python a one-off call is simpler as a Callable or Strategy. GoF itself does not require undo (it is an optional consequence, not part of the definition of Command). Command-as-a-class is justified when you have several of: undo, redo, queue, log, serialise, batch.

2. An undo that does not exactly reverse

class IncrementCounter:
    def execute(self): self._counter.value += 1
    def undo(self): self._counter.value = 0          # ← not -1!

Undo must return to exactly the state that existed before execute. Otherwise history is broken.

3. A Command that holds a reference to mutable shared state

class AddItem:
    def __init__(self, cart_ref):
        self._cart = cart_ref                         # ← shared mutable!
    def execute(self): self._cart.append(item)

If cart is changed from outside the command, undo may break the new state. Real systems often use a snapshot instead of a direct reference.


Observer + Command — together

A classic integration:

class InventoryService:
    def __init__(self, bus: EventBus):
        self._store: dict[str, int] = {}
        self._bus = bus
        self._history: list[Command] = []

    def execute(self, cmd: Command) -> None:
        cmd.execute()
        self._history.append(cmd)
        self._bus.publish("command_executed", {"cmd": cmd})  # ← Observer!


# Subscribers react to commands:
bus.subscribe("command_executed", audit_logger.log)
bus.subscribe("command_executed", metrics.increment)
bus.subscribe("command_executed", cache_invalidator.invalidate)

This is the foundation of Event Sourcing and CQRS architectures in larger systems.


Rules of thumb

Observer

  1. Callable as a listener is Pythonic. No separate Protocol needed.
  2. subscribe / unsubscribe are a pair. If only subscribe exists, prepare for memory leaks.
  3. Listeners should not depend on each other. Otherwise it is a procedure, not an Observer.
  4. Do not rely on the order of listener execution.
  5. For long operations, go async (asyncio, task queue).

Command

  1. Command is for when you need undo/queue/log/macro. Otherwise, a plain Callable.
  2. Undo must reverse exactly. Store _prev_state in execute.
  3. Command names are in domain terms. AddItemCommand, not Operation1.
  4. A Macro is Composite on top of Command. Same pattern at a different level.
  5. Transactional batch — execute_batch with rollback on failure.

One-line summary

Observer is "one publishes, many listen". Command is "a request as an object, with optional undo / queue / log". Together they are the foundation of event-driven architectures.