🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Design Patterns: Factory, Observer, and Strategy

Python PatternsđŸŸĸ Free Lesson

Design Patterns: Factory, Observer, and Strategy

Design patterns are vocabulary, not recipes. Their value in Python is mostly as shared names for structures you would otherwise reinvent — and because Python has first-class functions, dynamic attributes, and modules, a third of the Gang of Four catalogue collapses into one-liners that need no class at all. This lesson takes the patterns that still earn their keep: factories for construction you want to control, strategy for interchangeable algorithms, observer for decoupled notification, and command for reversible operations. It also covers the pattern most often taught first and applied worst, so you know why a module usually beats a singleton.

What You'll Learn

  • 1Map classic patterns onto Python idioms and know which ones can be skipped
  • 2Build a factory with a registry that supports extension without editing
  • 3Express strategy with plain callables instead of class hierarchies
  • 4Implement observer and command in ways that are testable and reversible

Which patterns survive Python

Many GoF patterns exist to compensate for languages without closures, dictionaries, or dynamic dispatch. Abstract Factory and Bridge address construction rigour in static languages; in Python, a dictionary of callables or a couple of keyword arguments does the same job with less machinery. Interpreter patterns give way to parser libraries. Memento is nearly free once you accept that copy and dataclasses.replace exist.

The patterns that keep their value are the ones expressing architecture rather than syntax: strategy for swappable behaviour, observer for event fan-out, command for undoable operations, and factory when construction logic itself has structure. The table below is the translation guide worth keeping — it tells you what to reach for and, more usefully, what not to build.

Classic patternPython idiomBuild the pattern when
StrategyFunction or lambda passed as an argumentThe algorithm must be selected at run time and extended by others
FactoryDictionary of classes plus a create functionConstruction needs validation, caching, or configuration
ObserverList of callbacks, weakref for lifetimesSubscribers come and go independently of the publisher
CommandClass with execute and undo, or a closure pairYou need queueing, logging, or reversal of operations
SingletonModule-level objectYou genuinely need one shared instance
Template methodBase class calling overridable stepsSteps are fixed but their implementations vary
Decorator (GoF)The @decorator syntax itselfWrapping behaviour is the whole requirement

Read the third column before adopting anything from the first. A pattern is justified when the relationship it describes will change independently; if two things will always change together, separate classes add seams nobody needs.

Factory: controlling construction without a switch

Construction code grows branches as new variants appear, and callers start importing concrete classes they should not know about. A factory inverts that: callers name a kind, the factory resolves it to a class, and the resolution lives in one place where validation, caching, and default configuration fit naturally. The registry form — a dictionary populated at import time — lets plugins register themselves without editing the factory.

Two refinements make the difference between a demo and something usable. Resolve lazily: store classes, not instances, unless construction is expensive and the object is stateless, because eager instances freeze configuration before the caller supplies it. And fail with a message listing the valid keys, so a typo produces an actionable error rather than a KeyError naming one missing string.

python
class CsvSource:
    def __init__(self, path):
        self.path = path
    def read(self):
        return f"csv:{self.path}"

class JsonSource:
    def __init__(self, path, indent=2):
        self.path = path
        self.indent = indent
    def read(self):
        return f"json:{self.path}({self.indent})"

REGISTRY = {"csv": CsvSource, "json": JsonSource}

def register(kind, cls):
    if not callable(cls):
        raise TypeError("factory entries must be callable")
    REGISTRY[kind] = cls
    return cls

def create_source(kind, **options):
    cls = REGISTRY.get(kind)
    if cls is None:
        raise KeyError(f"unknown source {kind!r}; available: {sorted(REGISTRY)}")
    return cls(**options)

print(create_source("csv", path="in.csv").read())        # csv:in.csv
print(create_source("json", path="in.json").read())      # json:in.json(2)

try:
    create_source("yaml")
except KeyError as exc:
    print("rejected:", exc)

The register function doubles as a decorator when used as @register("parquet"), which is how plugin packages typically add kinds without a central edit. Keep registration idempotent — overwriting an existing kind silently is how one dependency quietly replaces another's implementation.

Strategy: behaviour as data

Strategy asks for several algorithms behind one interface, and Python answers with callables. There is no need for a Strategy base class, a Context holder, or a wrapper object: pass the function, store it on the instance, and call it. The remaining design work is deciding what a strategy is allowed to assume — the argument shape, the return contract, and whether it may hold state between calls.

The pattern earns its keep when strategies are selected at run time from configuration or plug-ins, when several strategies must be tested in isolation, or when the set grows independently of the caller. For two branches that will never change, an if remains clearer. Name strategies as module-level functions rather than inline lambdas when they carry logic: named functions have names in tracebacks and can be referenced by configuration strings.

python
import json
import urllib.parse

def as_json(payload):
    return json.dumps(payload, separators=(",", ":")), "application/json"

def as_form(payload):
    return urllib.parse.urlencode(payload), "application/x-www-form-urlencoded"

def as_csv(payload):
    rows = [",".join(str(v) for v in row) for row in payload]
    return "\n".join(rows), "text/csv"

ENCODERS = {"json": as_json, "form": as_form, "csv": as_csv}

class Request:
    def __init__(self, encoder="json"):
        self.encoder = ENCODERS[encoder]

    def send(self, payload):
        body, content_type = self.encoder(payload)
        return {"content_type": content_type, "body": body, "bytes": len(body)}

print(Request("json").send({"a": 1})["body"])     # {"a":1}
print(Request("form").send({"a": 1})["body"])     # a=1
print(Request("csv").send([("a", "b"), (1, 2)])["content_type"])   # text/csv

Because a strategy is just a function, swapping one is a constructor argument, and testing one is a direct call with a literal. That is the whole pattern — the class exists only to hold the chosen behaviour, which in larger designs becomes a sort_key, a retry_policy, or a render hook on an object that already has other responsibilities.

Observer: fan-out without coupling

Observer keeps a publisher unaware of who consumes its events: subscribers register callbacks, and the publisher invokes them on state change. In Python this is a list of callables, and the interesting decisions are lifecycle ones. Storing strong references keeps subscribers alive longer than intended — a bound method keeps its instance alive — and a subscriber that raises can abort notification for everyone else unless you isolate each call.

The robust version stores weak references to bound methods, removes dead entries as it goes, and wraps each callback so one failure cannot silence the rest. Whether to continue after a failure is a policy decision: for telemetry you continue and log; for transactions where every listener must succeed, you collect errors and report them together.

python
import traceback
import weakref

class EventDispatcher:
    def __init__(self):
        self._listeners = {}
        self.errors = []

    def subscribe(self, event, callback):
        self._listeners.setdefault(event, []).append(callback)
        return lambda: self._listeners[event].remove(callback)

    def emit(self, event, payload):
        for callback in list(self._listeners.get(event, [])):
            try:
                callback(payload)
            except Exception as err:
                self.errors.append((event, err))
                traceback.print_exc()
        return self.errors

bus = EventDispatcher()
seen = []

bus.subscribe("order.created", lambda order: seen.append(("audit", order)))
bus.subscribe("order.created", lambda order: seen.append(("email", order)))
bus.subscribe("order.created", lambda order: (_ for _ in ()).throw(RuntimeError("boom")))

bus.emit("order.created", 42)
print(seen)                       # [('audit', 42), ('email', 42)]
print(len(bus.errors))            # 1 — the failing listener did not stop the others

Real systems usually replace the hand-rolled list with a library or with blinker-style signal objects, but the mechanics stay the same. What matters operationally is ordering guarantees (invoke in registration order unless documented otherwise), removal (return an unsubscribe function), and isolation (never let one listener take down the publisher).

Command: reversible operations

Command wraps an action and its parameters as an object, which buys three things: queueing, logging, and undo. Any time you need an operation you can store, transmit, or reverse — an editor's history, a job queue, a transactional step — the command shape fits. Python's version is small: an execute method, an undo method, and a history stack owned by an invoker.

The discipline that keeps undo honest is capturing state before mutation. An undo that tries to infer the previous value will fail on the second reversal; an undo that restores a snapshot taken at execute time cannot. For commands that touch external systems, record the inverse operation alongside the forward one and document which side effects are genuinely reversible.

python
class History:
    def __init__(self, target):
        self.target = target
        self._done = []
        self._undone = []

    def run(self, command):
        command.execute(self.target)
        self._done.append(command)
        self._undone.clear()

    def undo(self):
        if not self._done:
            return False
        command = self._done.pop()
        command.undo(self.target)
        self._undone.append(command)
        return True

    def redo(self):
        if not self._undone:
            return False
        command = self._undone.pop()
        command.execute(self.target)
        self._done.append(command)
        return True

class AppendText:
    def __init__(self, chunk):
        self.chunk = chunk
        self._previous = None
    def execute(self, doc):
        self._previous = len(doc)
        doc.append(self.chunk)
    def undo(self, doc):
        del doc[self._previous:]

doc = []
history = History(doc)
history.run(AppendText("hello"))
history.run(AppendText(" world"))
print("".join(doc))          # hello world
history.undo()
print("".join(doc))          # hello
history.redo()
print("".join(doc))          # hello world
print(history.undo())        # True

Note that execute records self._previous every time it runs, so redo-then-undo still restores correctly. That detail — capturing state at execution rather than in the constructor — is what makes a command history robust across arbitrary sequences of undo and redo.

Singleton, and why a module usually wins

Singleton exists to guarantee one instance, and Python already has a natural one: a module. Importing a module executes it once per process, the module namespace holds state, and functions defined there act as methods without any metaclass, lock, or __new__ override. When a single shared object is genuinely required, put it at module level or expose it through a function that creates it lazily.

Class-based singletons fail in ways that matter in tests and subclasses: they resist patching, they hold state across tests, and a metaclass version breaks multiple inheritance. If the requirement is really "one instance per context" — one per request, per thread, per tenant — a singleton is simply the wrong shape, and a context-managed instance passed explicitly is both clearer and testable.

python
# The module is the singleton: state lives once, access is ordinary
_SETTINGS = {"retries": 3, "timeout": 10}

def get_setting(key, default=None):
    return _SETTINGS.get(key, default)

def configure(**options):
    _SETTINGS.update(options)

# Lazy singleton when construction must be deferred
_instance = None

def get_cache():
    global _instance
    if _instance is None:
        _instance = {"hits": 0, "entries": {}}
    return _instance

configure(timeout=30)
print(get_setting("timeout"), get_setting("missing", "n/a"))   # 30 n/a
cache = get_cache()
cache["hits"] += 1
print(get_cache()["hits"], get_cache() is cache)               # 1 True

The lazy accessor keeps construction cost off the import path while still guaranteeing one object, and because the state sits in a module global, a test can reset it by assigning None. Compare that with a class-based singleton, where resetting means reaching into a metaclass dictionary — a strong hint that the module version was the right design all along.

Common Mistakes

Building a class hierarchy for a strategy that is one function

Fix: Pass the callable directly; add classes only when strategies carry shared state or several methods

Subscribing bound methods strongly and leaking the subscriber

Fix: Hold weak references or return an explicit unsubscribe function that callers wire up

Letting one observer exception abort the whole notification

Fix: Isolate each callback, record the error, and decide per event type whether to continue

Writing an undo that infers the previous state

Fix: Snapshot before mutation inside execute so reversal works after any sequence of redo

Implementing singleton with a metaclass when a module would do

Fix: Use a module-level object or a lazy accessor function, which tests can reset trivially

Best Practices

  • Name the relationship first, then check whether a plain function already expresses it
  • Keep factories lazy and fail with messages that list valid options
  • Give every subscriber registration a matching removal path
  • Record command state at execute time so undo stays correct across redo
  • Prefer modules and dependency injection over global instances for shared state

Interview Questions

Q1: How would you implement strategy in Python without classes?

Store the algorithm as a callable — a module-level function, lambda, or partial — on the object that uses it, and call it through a stable name. Classes are only needed when a strategy carries its own state or several cooperating methods.

Q2: What are the main pitfalls of the observer pattern?

Strong references that keep subscribers alive, no defined ordering, no removal path, and one failing listener aborting notification for the rest. A robust dispatcher uses weak references or explicit unsubscribe, documents ordering, and isolates callback failures.

Q3: Why is the singleton pattern less necessary in Python?

Modules are imported once per process and naturally provide a single shared namespace, so module-level state acts as a singleton without custom machinery — and unlike a class-based singleton, it can be reset in tests by reassigning the global.

Key Takeaways

  • Patterns are names for relationships; skip them when a function already says it
  • Factories centralise construction, validate options, and let plugins register themselves
  • Strategy in Python is a callable — the surrounding class is optional scaffolding
  • Observer needs lifecycle management: ordering, removal, and failure isolation
  • Command earns its keep through undo, which requires capturing state before mutation
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement