Swap the rule, not the whole feature
Picture
A flat delivery rule charges 50 units. A per-item rule charges 10 per item. Checkout’s question stays the same—what is the fee for this item count?—while one policy changes.
Predict
What is the smallest useful strategy representation in Python here?
Walk through the small example
A function taking the count and returning a fee. A dedicated class is optional unless the strategy needs more state or operations.
Mental model and complete Python solution
DeliveryQuote receives a callable instead of choosing a rule through hard-coded branches inside each quote. The caller selects policy at construction. Validate the shared input once at the boundary. Both strategies return nonnegative integer minor units, so their outputs mean the same thing. A varying algorithm is isolated without changing the workflow around it.
What the function promises: quote(count) accepts a nonnegative integer item count. The flat policy charges 50 even for zero items; the per-item policy charges 10 per item. This is an explicitly chosen example policy, not a universal delivery rule.
def flat_fee(count):
return 50
def per_item_fee(count):
return 10 * count
class DeliveryQuote:
def __init__(self, policy):
self.policy = policy
def quote(self, count):
if type(count) is not int or count < 0:
raise ValueError("Count must be a nonnegative integer")
return self.policy(count)
assert DeliveryQuote(flat_fee).quote(3) == 50
assert DeliveryQuote(per_item_fee).quote(3) == 30
assert DeliveryQuote(per_item_fee).quote(0) == 0
Work and storage: These two example policies are O(1). The surrounding workflow does not assume every future policy has the same computational cost.
When to recognize it: The workflow stays the same while one policy varies. Pass that policy in.
Check before applying it: If only one simple rule exists, a function may be enough. A pattern name does not justify a class hierarchy.
Change one rule
A new policy needs a distance as well as item count. Can it silently reinterpret count as distance?
See what changes
No. That breaks the shared contract. Introduce an explicit input object carrying both fields, or a different interface, and update callers deliberately.
Connect
Let small objects work together: The service has a policy; it is not a subtype of that policy.
Design a parking lot: Spot selection and pricing can vary independently of parking state.