Strategy
Strategy replaces a hard-coded algorithm with a pluggable callable or object. The context calls strategy.execute(...) and does not know which variant it is.
Detailed Explanation
Shipping has ground, air, and pickup. A pile of if method == "air" in checkout grows every time you add a carrier. Strategy moves each algorithm to its own function or class and stores the current one on the order or the checkout service.
In Java you declare an interface and three classes. In Python a function is enough: checkout(cart, ship=ship_air). First-class functions are the pattern. A class with __call__ or an execute method is useful when the strategy has configuration (AirStrategy(max_kg=30)).
The context should depend on a small protocol: def ship(order) -> Receipt. A Protocol documents it for checkers. Duck typing documents it for humans. Do not make strategies inherit from a base unless they share code.
Selection can be a dict of strategies (CARRIERS[name]), a factory, or injection at construction. Avoid a global current_strategy unless you like hidden state in tests.
Strategies should not reach back into the context's private fields. Pass what they need. If they need everything, you have not split a strategy; you have split a method in two files.
sorted(..., key=) is strategy. str.splitlines vs a custom parser as a parameter is strategy. Once you see the name, you will find it everywhere you already pass a function.
Code Examples
def ship_ground(order: dict) -> int:
return 500 + 50 * order["kg"]
def ship_air(order: dict) -> int:
return 2000 + 120 * order["kg"]
def postage(order: dict, ship) -> int:
return ship(order)
print(postage({"kg": 2}, ship_air)) # 2240class PercentOff:
def __init__(self, rate: float):
self.rate = rate
def apply(self, cents: int) -> int:
return int(cents * (1 - self.rate))
def checkout(cents: int, discount) -> int:
return discount.apply(cents)
print(checkout(1000, PercentOff(0.1))) # 900Common Gotchas
Strategy that imports the context's internals
you cannot reuse it. Pass data.
A dict of strategies with missing keys
raise a clear `ValueError`, do not fall through to `None`.
Stateful strategies shared across requests
a class instance with mutable counters needs a lock or a new instance per request.
A `lambda` is a strategy
name it once it has a body or a test.