Strategy: Replace an Algorithm
Standard and express delivery calculate fees differently. Repeating delivery-type branches throughout order code makes additions expensive. Strategy separates an algorithm that callers may replace.
A Python function can be a strategy
def standard(weight):
return 3000 if weight <= 2 else 5000
def express(weight):
return standard(weight) + 4000
class ShippingQuote:
def __init__(self, calculate):
self.calculate = calculate
def fee(self, weight):
return self.calculate(weight)
print(ShippingQuote(standard).fee(1))
print(ShippingQuote(express).fee(1))
The outputs are 3000 and 7000. ShippingQuote only passes weight and receives a result. Functions are values, so each calculation need not become a class. An object may be useful when a strategy carries substantial configuration or state.
Strategies must honor the same contract. Returning won from one and dollars from another prevents safe substitution.
What remains?
Some code still selects the strategy based on input or configuration. The pattern does not eliminate every conditional; it prevents selection and calculation from being repeatedly mixed together.
Check your understanding
There is one stable shipping rule. Should you create several strategy classes immediately?
Show explanation
A small function may be sufficient. Introduce the separation when calculations need replacement or isolation in tests, considering the extra structure readers must understand.