Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Design patterns

By the end of this chapter, you'll be able to

  • Replace a cascade of ifs with the Strategy pattern
  • Decouple an event from its reactions with the Observer pattern
  • Centralise object creation with a factory
  • Recognise when a pattern needlessly complicates the code

Strategy: choosing an algorithm at run time

A shop computes delivery fees differently depending on the chosen mode. The naive version piles up ifs in a single function, which must be reopened for every new mode. The Strategy pattern puts each computation in its own function, and chooses the right one at run time. In Python, since a function is a value, a plain dictionary is enough:

def shop_pickup(weight_kg, distance_km):
    return 0

def motorbike(weight_kg, distance_km):
    return 500 + 100 * distance_km

def van(weight_kg, distance_km):
    return 2000 + 50 * distance_km + 20 * weight_kg

STRATEGIES = {"pickup": shop_pickup, "motorbike": motorbike, "van": van}

def delivery_fee(mode, weight_kg, distance_km):
    return STRATEGIES[mode](weight_kg, distance_km)

for mode in STRATEGIES:
    print(f"{mode:<10} {delivery_fee(mode, 12, 8):>6} FCFA")
pickup          0 FCFA
motorbike    1300 FCFA
van          2640 FCFA

Adding a mode (the cargo bike, for example) means writing a function and adding it to the dictionary: delivery_fee does not change. This is the open/closed principle: code that is open to extension, but closed to modification.

Observer: notifying without knowing

When an order is paid, a receipt must be sent, the stock updated and delivery notified. If the payment function calls these three services directly, it depends on all of them. With the Observer pattern, it just publishes an event; interested parties subscribe to it:

class Events:
    def __init__(self):
        self.subscribers = {}

    def subscribe(self, name, function):
        self.subscribers.setdefault(name, []).append(function)

    def publish(self, name, **data):
        for function in self.subscribers.get(name, []):
            function(**data)

bus = Events()
bus.subscribe("order_paid", lambda order, amount: print(f"Receipt sent: order {order}, {amount} FCFA"))
bus.subscribe("order_paid", lambda order, amount: print(f"Stock updated for order {order}"))
bus.subscribe("order_paid", lambda order, amount: print(f"Rider notified for order {order}"))

def pay(order, amount):
    # … payment validation …
    bus.publish("order_paid", order=order, amount=amount)

pay(1042, 15500)
Receipt sent: order 1042, 15500 FCFA
Stock updated for order 1042
Rider notified for order 1042

pay knows nothing about receipts, stock or delivery. Adding a reaction (a thank-you message, a statistic) does not require changing it: one new subscription is enough.

Subscribers can be added or removed without touching the payment.

Step 5 of 5
Text description of the animation
  1. The payment is validated.
  2. Instead of calling each service, it publishes an event.
  3. The bus calls each subscriber, in subscription order.
  4. Each subscriber does its job, independently of the others.
  5. Subscribers can be added or removed without touching the payment.

Factory: creating the right object

When the type of object to create depends on a configuration (“send notifications by SMS or by email?”), a factory centralises the decision. The rest of the program asks for “a notifier” without caring what kind it is:

class SMSNotifier:
    def send(self, recipient, message):
        return f"SMS to {recipient}: {message[:30]}"

class EmailNotifier:
    def send(self, recipient, message):
        return f"Email to {recipient}: {message}"

def create_notifier(config):
    channels = {"sms": SMSNotifier, "email": EmailNotifier}
    try:
        return channels[config["channel"]]()
    except KeyError:
        raise ValueError(f"unknown channel: {config.get('channel')}") from None

for config in ({"channel": "sms"}, {"channel": "email"}):
    n = create_notifier(config)
    print(n.send("Fatou", "Your order 1042 is on its way, delivery expected tomorrow."))
SMS to Fatou: Your order 1042 is on its way,
Email to Fatou: Your order 1042 is on its way, delivery expected tomorrow.

The SMS is cut to 30 characters for the example. The factory also checks the configuration: a misspelt channel raises a clear error at start-up, rather than an obscure crash at sending time.

Mini-lab: a new strategyPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: a subscriber that unsubscribes

Add an unsubscribe(name, function) method to the event bus, then check that after unsubscribing, the subscriber no longer receives events. Use a log list to record what each subscriber receives, instead of printing.

Hint 1
To unsubscribe a function, you must keep a reference to it: use a named function, not a lambda written directly in the call.
Hint 2
list.remove(function) removes the first occurrence of the function.
Show the solution and common mistakes
class Events:
    def __init__(self):
        self.subscribers = {}
    def subscribe(self, name, function):
        self.subscribers.setdefault(name, []).append(function)
    def unsubscribe(self, name, function):
        if function in self.subscribers.get(name, []):
            self.subscribers[name].remove(function)
    def publish(self, name, **data):
        for function in list(self.subscribers.get(name, [])):
            function(**data)

log = []
def receipt(order):
    log.append(f"receipt {order}")
def statistic(order):
    log.append(f"stat {order}")

bus = Events()
bus.subscribe("paid", receipt)
bus.subscribe("paid", statistic)
bus.publish("paid", order=1)
bus.unsubscribe("paid", statistic)
bus.publish("paid", order=2)
print(log)
['receipt 1', 'stat 1', 'receipt 2']

list(self.subscribers.get(name, [])) goes through a copy of the list: a subscriber that unsubscribed during publication would not disturb the current loop.

Common mistakes:

  • Subscribing a lambda then trying to unsubscribe it with another seemingly identical lambda: they are two different objects, and the first stays subscribed.
  • Changing the list of subscribers while going through it: some subscribers can be skipped. Going through a copy avoids the problem.

Summary

  1. 1Strategy: each variant of a computation in its own function, chosen at run time, often through a dictionary.
  2. 2Open/closed: variants are added without changing the code that uses them.
  3. 3Observer: an event is published, and subscribers react without the publisher knowing them.
  4. 4Factory: creating the right object from the configuration is centralised and checked.
  5. 5A pattern has a cost: introduce it when a real need appears, not “just in case”.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.