Python Design Patterns
Strategy Pattern in Python
Swap the algorithm at run time, such as a pricing rule, instead of writing a long if / elif chain.
What you'll learn
- Interchangeable algorithms
- Passing functions as strategies
- Composition over conditionals
Checkout(member_discount).total(15)
Checkoutregular_discountmember_discount→ 12.00
Plug in the algorithm
Strategy moves varying algorithms behind a common callable or interface and favors composition over conditionals.
Key points
- Each strategy is a function or class with the same signature.
- The context receives a strategy and calls it.
- Adding a new rule means adding a strategy, not editing an if chain.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
def regular_discount(total): return total
def member_discount(total): return total * 0.8
class Checkout:
# Strategy: inject the algorithm that is allowed to vary.
def __init__(self, discount_strategy):
self.discount_strategy = discount_strategy
def total(self, amount):
# Delegate the varying algorithm to the strategy.
return self.discount_strategy(amount)
checkout = Checkout(member_discount)
print(f"{checkout.total(15):.2f}")
Result of running the code
12.00
Code explanation
Checkout delegates discount calculation to the injected strategy function.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges