Strategy and Template Method Lab
Retrieval Prompts
- State the three roles in Strategy and what each knows about the others.
- State the difference between a Strategy object and a function reference, and when each is preferable.
- State the difference between Strategy and Template Method in one sentence.
- State what the "template method" itself is allowed to do and not to do.
- State one case where introducing Strategy is over-engineering.
Compare and Distinguish
Separate these pairs clearly:
- Strategy versus Template Method
- Strategy object versus closure
- "Replace Conditional with Polymorphism" versus a match/switch on an enum
- interface with one method versus a function type
- hook method versus abstract method
Common Mistake Check
Identify the error in each:
- "I extracted Strategy for the one discount formula we have. Done."
- "The context has
if strategy instanceof FreeShippingto log a special case. It's fine -- it's only one line." - "All our AI bots subclass
GameAI, but each overridesturn()to change the step order." - "Every validator has
validate(input): booland no state; we made each one a class because it feels cleaner." - "Our sort takes a list of comparator objects. When we need a second-level tie-breaker we add a boolean flag to the interface."
Mini Application
For each scenario:
- Decide: Strategy, Template Method, plain function, or none.
- Sketch the interface.
- Name the one axis of variation in one phrase.
- Note one simpler alternative.
Scenarios:
- Password hashing where the algorithm may switch from bcrypt to argon2 without redeploy.
- Pricing engine where 80% of the algorithm is identical and only two steps differ by product category.
- Validating a user-submitted form field. Ten rule types.
- Ordering a list of items by any user-chosen column.
- Image filter pipeline where the pipeline order is fixed but individual filters vary.
Refactor Drill
Take this switch-on-type function and refactor it to Strategy, then to closure-based if appropriate:
def fee(kind, amount):
if kind == "basic": return 0.00
if kind == "silver": return amount * 0.02
if kind == "gold": return max(1.00, amount * 0.015)
if kind == "vip": return 0.00
raise ValueError(kind)
Target: call sites compute fee through an interface; adding a sixth tier requires no change to existing tiers or the caller.
Evidence Check
This page is complete only if you can justify each pattern choice by naming the axis of variation and the simpler alternative you rejected.