Lesson 6 of 12 Design Patterns

Behavioral Patterns: Strategy, Observer, State

Strategy, observer, state and command patterns in runnable Python: swap algorithms, publish events, enforce order lifecycles and support undo.

40-50 min intermediate 0/12 lessons done
Course contents Lesson 6 of 12 · 0 done
On this page (10 sections)
  1. What you will learn
  2. The code
  3. Strategy
  4. Observer
  5. State
  6. Command
  7. Others worth knowing by name
  8. Key takeaways
  9. Exercises
  10. Quiz

What you will learn

  • The four behavioural patterns that appear most in LLD case studies.
  • How State turns invalid transitions into clear errors.
  • How Command enables undo, queues and audit logs.

The code

"""Behavioral patterns: strategy, observer, state and command."""
from abc import ABC, abstractmethod


# --- Strategy: swap an algorithm at runtime ------------------------------------
def by_price(p):
    return p["price"]


def by_rating(p):
    return -p["rating"]


def sort_products(products, strategy):
    return [p["name"] for p in sorted(products, key=strategy)]


# --- Observer: notify subscribers when something happens ------------------------
class EventBus:
    def __init__(self):
        self.subscribers = {}

    def subscribe(self, event, handler):
        self.subscribers.setdefault(event, []).append(handler)

    def publish(self, event, payload):
        for handler in self.subscribers.get(event, []):
            handler(payload)


# --- State: behaviour depends on the current state object -----------------------
class OrderState(ABC):
    name = "?"

    def pay(self, order):
        raise ValueError(f"cannot pay when {self.name}")

    def ship(self, order):
        raise ValueError(f"cannot ship when {self.name}")

    def cancel(self, order):
        raise ValueError(f"cannot cancel when {self.name}")


class Created(OrderState):
    name = "CREATED"

    def pay(self, order):
        order.state = Paid()

    def cancel(self, order):
        order.state = Cancelled()


class Paid(OrderState):
    name = "PAID"

    def ship(self, order):
        order.state = Shipped()

    def cancel(self, order):
        order.state = Cancelled()  # a refund would be triggered here


class Shipped(OrderState):
    name = "SHIPPED"


class Cancelled(OrderState):
    name = "CANCELLED"


class Order:
    def __init__(self):
        self.state = Created()

    def pay(self):
        self.state.pay(self)

    def ship(self):
        self.state.ship(self)

    def cancel(self):
        self.state.cancel(self)


# --- Command: wrap an action as an object (enables undo, queues, logging) --------
class TextEditor:
    def __init__(self):
        self.text = ""
        self.history = []

    def run(self, command):
        command.do(self)
        self.history.append(command)

    def undo(self):
        if self.history:
            self.history.pop().undo(self)


class Append:
    def __init__(self, s):
        self.s = s

    def do(self, ed):
        ed.text += self.s

    def undo(self, ed):
        ed.text = ed.text[: len(ed.text) - len(self.s)]


if __name__ == "__main__":
    items = [{"name": "A", "price": 30, "rating": 4.1}, {"name": "B", "price": 10, "rating": 3.9},
             {"name": "C", "price": 20, "rating": 4.8}]
    print("by price:", sort_products(items, by_price), "by rating:", sort_products(items, by_rating))

    bus = EventBus()
    bus.subscribe("order_paid", lambda o: print("email: receipt for", o))
    bus.subscribe("order_paid", lambda o: print("warehouse: pack", o))
    bus.publish("order_paid", "order-17")

    order = Order()
    order.pay()
    order.ship()
    try:
        order.cancel()
    except ValueError as e:
        print("state:", order.state.name, "|", e)

    ed = TextEditor()
    ed.run(Append("Hello"))
    ed.run(Append(", world"))
    ed.undo()
    print("editor:", repr(ed.text))

Output:

by price: ['B', 'C', 'A'] by rating: ['C', 'A', 'B']
email: receipt for order-17
warehouse: pack order-17
state: SHIPPED | cannot cancel when SHIPPED
editor: 'Hello'

Strategy

A family of interchangeable algorithms behind one interface. Here a strategy is just a function passed to sort_products; in Java it would be an interface like Comparator. You’ve already seen strategies in this course: discount policies in the SOLID lesson, and you’ll see pricing and spot-allocation strategies in the parking lot.

Use it when you’d otherwise write if mode == "a": ... elif mode == "b": ... for an algorithm choice.

Observer

Subscribers register interest; the publisher notifies all of them without knowing who they are. After payment, the email service and the warehouse both react, and adding an analytics subscriber needs no change to the payment code.

Watch out for:

  • Ordering and failure: one slow or failing handler shouldn’t block the others. Production systems often publish to a message queue instead of calling handlers inline (see message queues in the System Design course).
  • Memory leaks: subscribers that are never removed keep objects alive.

State

An order’s allowed actions depend on its state. Without the pattern you get if self.status == "PAID" and ... checks spread across every method. With State:

  • Each state class defines only the transitions it allows; the base class rejects everything else.
  • Adding a Returned state means adding a class, not editing every method.
  • Invalid actions fail loudly: cancelling a shipped order raises cannot cancel when SHIPPED.

For small lifecycles an enum with a transition table (ALLOWED = {CREATED: {PAID, CANCELLED}, ...}) is a fine lighter alternative. You’ll see the State pattern again in the vending machine.

Command

Each action becomes an object with do and undo. The editor keeps a history stack, so undo pops the last command. Commands also make it easy to:

  • Queue work for later (job queues are commands serialized to messages).
  • Log every action for audit or replay.
  • Implement redo with a second stack.

Others worth knowing by name

  • Template method: a base class defines the steps of an algorithm and subclasses fill in some steps.
  • Chain of responsibility: a request passes through handlers until one deals with it (middleware, approval workflows, ATM note dispensing).
  • Iterator: walk a collection without exposing its structure (Python generators).

Key takeaways

  • Strategy swaps algorithms; Observer broadcasts events to decoupled subscribers.
  • State moves lifecycle rules into state classes, making invalid transitions explicit errors.
  • Command turns actions into objects, enabling undo, queues and audit logs.

Exercises

  1. Add a Returned state reachable only from Shipped, and test that Created can’t be returned.
  2. Add redo support to the text editor.
  3. Make EventBus.publish keep calling the remaining handlers when one raises, and collect the errors.

Quiz

  1. Which pattern fits “choose a pricing algorithm based on the customer’s plan”?
  2. What happens when you call ship() on a Created order, and why?
  3. What does the Command pattern need to support undo?
Show answers
  1. Strategy.
  2. It raises cannot ship when CREATED, because Created doesn’t override ship, so the base OrderState.ship rejects it.
  3. Each command must know how to reverse itself (undo), and the invoker must keep a history of executed commands.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).