The Strategy Pattern
Shelfwise's price_order has grown an if/elif chain: no discount, member 10% off, buy three get the cheapest free. The festival sale starts next week with a fourth rule, and nobody wants to edit a function that every order goes through. Strategy is the pattern built for exactly this.
The rule
Put each interchangeable algorithm in its own object, and hand in the one you need.
Strategy has three roles:
- Strategy interface: the one method every variant offers.
- Concrete strategies: one class per variant.
- Context: the code that uses a strategy without knowing which one it has.
class DiscountStrategy(ABC):
@abstractmethod
def discount(self, order): ...
class NoDiscount(DiscountStrategy):
def discount(self, order):
return 0
class MemberDiscount(DiscountStrategy):
def discount(self, order):
return order.subtotal() * 0.10
class ThreeForTwo(DiscountStrategy):
def discount(self, order):
prices = sorted(line.price for line in order.lines)
return prices[0] if len(prices) >= 3 else 0
def price_order(order, strategy: DiscountStrategy):
return order.subtotal() - strategy.discount(order)price_order is the context. It has no conditions at all. For the festival sale you write FestivalDiscount and pass it in; nothing else changes. Each rule is also small enough to unit-test alone.
(To keep the example short, ThreeForTwo treats each order line as one book. A real version would account for quantities.)
Strategy is the design principles you already know, packaged: encapsulate what varies (the discount rule), program against an abstraction (DiscountStrategy), composition (the context holds a strategy) and Open/Closed (new rules are new classes).
In Python, a strategy can even be a plain function: price_order(order, member_discount). Functions are values, so a one-method interface often collapses into a callable. The pattern is the same idea either way. Choose a class when a strategy needs its own settings, such as PercentOff(15), and a function when it does not.