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

Strategy, Command, and Adapter Patterns in Python

Python PatternsđŸŸĸ Free Lesson

Strategy, Command, and Adapter Patterns in Python

A design pattern is a named answer to a question that keeps recurring: how do I swap an algorithm, how do I make an action reversible, how do I sit behind an interface I cannot change. The GoF catalogue was written for languages where a class is the only unit of composition, and Python's first-class functions, duck typing, and dynamic attribute lookup reshape all three answers. This lesson implements Strategy, Command, and Adapter in full, then shows the Python-shaped shortcut for each and the point where the machinery starts costing more than it saves.

What You'll Learn

  • 1Implement Strategy with a protocol and swap implementations at runtime
  • 2Build a Command with undo, redo, and serialisable history
  • 3Adapt a third-party interface without editing its source
  • 4Decide when a plain function or a dict registry replaces a whole pattern

Patterns are answers to questions you keep being asked

Strategy appears when one task has several correct algorithms and the choice must move out of the calling code: sorting by different keys, pricing by different rules, exporting to different formats. Command appears when a request has to be stored, queued, logged, undone, or replayed: editor operations, job queues, macro recorders. Adapter appears when you must call a library whose method names, argument order, or error conventions differ from the ones your code already depends on.

The value of naming them is not ceremony. A named pattern lets you state the constraint in review — "the discount rule must be swappable per tenant" — and gives the team a shared vocabulary for the trade-off. The danger begins when the name becomes the goal and classes proliferate for a behaviour that one function would have covered.

Strategy: one behaviour, several algorithms, zero conditionals

The classical form defines a common interface, gives each algorithm a class, and lets the context hold a reference to whichever one it was configured with. The example below prices an order under three rules, and the pricing function never branches on which rule is active.

python
from typing import Protocol


class PricingRule(Protocol):
    def price(self, subtotal: float, units: int) -> float: ...


class Standard:
    def price(self, subtotal: float, units: int) -> float:
        return subtotal


class PercentageOff:
    def __init__(self, percent: float) -> None:
        self.percent = percent

    def price(self, subtotal: float, units: int) -> float:
        return subtotal * (1 - self.percent / 100)


class BulkDiscount:
    def __init__(self, every: int, rate: float) -> None:
        self.every = every
        self.rate = rate

    def price(self, subtotal: float, units: int) -> float:
        free_units = units // self.every
        discount = (subtotal / units) * free_units * self.rate
        return max(0.0, subtotal - discount)


def checkout(rule: PricingRule, subtotal: float, units: int) -> float:
    return round(rule.price(subtotal, units), 2)


print(checkout(Standard(), 100.0, 4))               # 100.0
print(checkout(PercentageOff(10), 100.0, 4))        # 90.0
print(checkout(BulkDiscount(every=3, rate=1.0), 90.0, 9))  # 60.0

Note what the Protocol buys: structural typing means a strategy does not inherit from anything, so third-party classes can be dropped in as long as they respond to price. A base class would have forced every implementation to import your module.

When the strategy is really just a function

Once you notice that a strategy is "a callable with a fixed signature", the class hierarchy often collapses. Functions are values: they can live in a dictionary, be selected by a configuration key, and be replaced at runtime without a class definition anywhere.

python
def percent_off(subtotal: float, units: int, percent: float) -> float:
    return subtotal * (1 - percent / 100)


def bulk(subtotal: float, units: int, every: int) -> float:
    free_units = units // every
    return subtotal - (subtotal / units) * free_units


RULES = {
    "standard": lambda sub, units: sub,
    "ten_off": lambda sub, units: percent_off(sub, units, 10),
    "buy_3_get_1": lambda sub, units: bulk(sub, units, 3),
}


def checkout(rule_name: str, subtotal: float, units: int) -> float:
    try:
        rule = RULES[rule_name]
    except KeyError:
        raise ValueError(f"unknown pricing rule: {rule_name}") from None
    return round(rule(subtotal, units), 2)


print(checkout("buy_3_get_1", 90.0, 9))  # 60.0

Keep the class form when a strategy carries state, implements several related methods, or must be instantiated once and shared. Reach for the function form when the behaviour is a single expression plus configuration — which covers most pricing, formatting, and filtering rules.

Command: every action as an object you can reverse

The Command pattern turns a request into an object with execute and undo, so a history stack becomes trivial and operations can be queued, logged, or serialised for a worker process. The design below supports redo as well by keeping the undone commands instead of discarding them.

python
from dataclasses import dataclass, field


class Document:
    def __init__(self) -> None:
        self.text = ""

    def insert(self, position: int, chunk: str) -> None:
        self.text = self.text[:position] + chunk + self.text[position:]

    def delete(self, position: int, length: int) -> str:
        removed = self.text[position:position + length]
        self.text = self.text[:position] + self.text[position + length:]
        return removed


@dataclass
class Insert:
    doc: Document
    position: int
    chunk: str
    _removed: str = field(default="", repr=False)

    def execute(self) -> None:
        self.doc.insert(self.position, self.chunk)

    def undo(self) -> None:
        self._removed = self.doc.delete(self.position, len(self.chunk))

    def redo(self) -> None:
        self.doc.insert(self.position, self._removed or self.chunk)


class History:
    def __init__(self, doc: Document) -> None:
        self.doc = doc
        self.past: list[Insert] = []
        self.future: list[Insert] = []

    def run(self, command: Insert) -> None:
        command.execute()
        self.past.append(command)
        self.future.clear()

    def undo(self) -> None:
        if self.past:
            command = self.past.pop()
            command.undo()
            self.future.append(command)

    def redo(self) -> None:
        if self.future:
            command = self.future.pop()
            command.redo()
            self.past.append(command)


h = History(Document())
h.run(Insert(h.doc, 0, "hello "))
h.run(Insert(h.doc, 6, "world"))
print(h.doc.text)   # hello world
h.undo()
print(h.doc.text)   # hello
h.redo()
print(h.doc.text)   # hello world

Two details matter in interviews. Redo must clear the future stack the moment a new command runs, otherwise you resurrect operations the user abandoned. And commands should capture enough state (here _removed) to be inverted without replaying history from the start.

Adapter: the interface is not yours to change

An adapter presents the interface your code expects while delegating to the object you actually have. You reach for it when a vendor SDK uses plug_in_type_a, when a legacy function returns (code, body) tuples instead of raising, or when you need to introduce a new interface gradually across a large codebase.

python
class StripeLikeGateway:
    def charge(self, amount_cents: int, token: str) -> dict:
        if amount_cents <= 0:
            raise ValueError("amount must be positive")
        return {"status": "ok", "charged": amount_cents, "tok": token}


class Payments(Protocol):
    def charge(self, amount: float, currency: str, token: str) -> dict: ...


class GatewayAdapter:
    def __init__(self, gateway: StripeLikeGateway) -> None:
        self.gateway = gateway

    def charge(self, amount: float, currency: str, token: str) -> dict:
        if currency != "USD":
            raise ValueError(f"only USD supported, got {currency}")
        result = self.gateway.charge(round(amount * 100), token)
        return {
            "status": result["status"],
            "amount": result["charged"] / 100,
            "currency": currency,
        }


print(GatewayAdapter(StripeLikeGateway()).charge(12.5, "USD", "tok_1"))

The adapter owns the translation rules — money units, currency policy, response shape — and your application code only ever sees Payments. Because Python has no required interface, the "adapter" is often a single wrapper function; introduce the class when the translation needs state or several methods.

Testing code that has patterns in it

Indirection makes tests easier to write, not harder, as long as you test the seams each pattern creates. For Strategy, the seam is the interface: write one contract test that asserts the behaviour every pricing rule must satisfy — non-negative result, correct rounding, unchanged input — and run it once per registered rule. Adding a rule then either passes the shared contract or fails it, which is exactly the guarantee you wanted from the abstraction.

For Command, the seam is the state transition. A table-driven test that executes a command, undoes it, and asserts the document equals its original value catches the majority of real bugs, because undo is where implementations lose information. Redo deserves its own case, plus a test that a new command after an undo clears the future stack.

For Adapter, test against a fake of the third-party object rather than the real SDK: assert both the happy path and the translation rules — currency conversion, error mapping, field renaming. Keep one thin integration test that runs the adapter against the real client in CI, because a fake you wrote yourself happily agrees with your own mistakes.

Choosing among the three, and what each one costs

PatternThe question it answersPython-shaped formTypical overhead
StrategyWhich algorithm runs?Function, Protocol, or class behind one methodLow; a registry lookup
CommandHow do I store, undo, or replay a request?Dataclass with execute and undoMedium; history must be bounded
AdapterHow do I talk to something I cannot edit?Thin wrapper class or functionLow; grows if it starts caching

Pick Strategy when the choice is known at configuration time and the algorithm is the variable part. Pick Command when the request itself has a lifetime — queued, retried, logged, reversed. Pick Adapter at system boundaries where two vocabularies meet; if you are adapting your own code to itself, the design is wrong, not the interface.

Where pattern worship goes wrong

The failure mode is uniform: an interface with one implementation, a strategy selected by an if that could have been a dict entry, an adapter wrapping a class that already exposes the right method. Each adds a file, an indirection, and a place for a future reader to get lost. Python rewards you for expressing the simplest correct structure first and introducing a named pattern only when a concrete requirement — swappability, reversibility, boundary translation — forces it.

Common Mistakes

Building a class hierarchy for a strategy that is one arithmetic expression

Fix: Use a plain function in a dict registry and promote it to a class only when it needs state or several methods

Forgetting to clear the redo stack when a new command executes

Fix: Empty the future list inside run so abandoned operations can never be replayed

Writing an adapter that silently converts errors into default values

Fix: Translate the error type explicitly and raise; a swallowed failure at a boundary is impossible to debug downstream

Making every pattern a global singleton so call sites skip passing collaborators

Fix: Inject the strategy or gateway as an argument; hidden globals make unit tests and parallel configurations painful

Best Practices

  • Type the strategy interface with typing.Protocol so external classes can conform without inheriting
  • Keep commands small and serialisable; a command that cannot be reconstructed cannot be queued or audited
  • Put adapters at the edge of the system and keep domain code free of vendor field names
  • Give the registry a single owner module so adding a rule never requires editing business logic
  • Write a test that swaps every registered strategy at runtime; if one swap needs a code change, the abstraction is leaking

Interview Questions

Q1: How is the Strategy pattern different from a simple if statement?

An if statement couples the selection logic to every implementation in one place, so adding a rule means editing and retesting that branch. A strategy moves each algorithm behind one interface, keeps selection in configuration, and lets callers depend only on the interface.

Q2: What must a Command support to be usable in an editor?

Execute, undo, and enough captured state to redo or re-execute later. It should also be safe to run twice for retries, which means no hidden side effects outside the object it manipulates.

Q3: Adapter versus Decorator: what is the difference?

An adapter changes the interface so a client can call an object that does not match. A decorator keeps the interface and adds behaviour around the same calls. Adapter fixes incompatibility, decorator extends responsibility.

Q4: When would you refuse to implement a pattern a colleague asked for?

When there is exactly one implementation and no swappable axis, or when the indirection hides a branch that tests must still cover. Patterns pay for themselves at real variation points, not at speculative ones.

Key Takeaways

  • Strategy isolates the algorithm that varies, and in Python it is often a function in a dict rather than a class hierarchy
  • Command turns a request into data, which is what makes undo, redo, queues, and audit logs possible
  • Adapter translates between vocabularies at a system boundary and belongs in its own module, not in domain logic
  • Protocol-based typing lets unrelated classes satisfy a pattern interface without importing it
  • Every pattern adds indirection; introduce one only when a named requirement forces it
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