Strategy Pattern in Python
Strategy moves varying algorithms behind a common callable or interface and favors composition over conditionals.
What is Strategy Pattern?
Strategy moves varying algorithms behind a common callable or interface and favors composition over conditionals.
Select an interchangeable algorithm at runtime.
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}")
Expected output
12.00
How it works
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.