Strategy Design Pattern¶
Swap algorithms without rewriting the object that uses them.
The Strategy Pattern separates what a system does from how that behavior is chosen.
Business Framing¶
A pricing engine may need different rules for:
retail customers
wholesale buyers
VIP members
The checkout flow should not be rewritten every time pricing policy changes. Instead, the checkout uses a pricing strategy object.
Visual Intuition¶
Pattern Anatomy¶
| Part | Responsibility |
|---|---|
| Context | Uses a strategy to perform work |
| Strategy interface | Defines a common method |
| Concrete strategies | Implement the behavior differently |
Worked Example: Pricing Strategies¶
What changed and what stayed stable?
The Checkout class stayed stable. Only the pricing behavior changed. That is exactly why Strategy reduces branching chaos.
Why Not Just Use if/elif?¶
Small decisions can use plain conditionals. Strategy becomes valuable when:
behavior families keep growing
rules change independently of the caller
you want easier testing
you want to inject behavior dynamically
When Strategy Fits Best¶
| Good fit | Weak fit |
|---|---|
| Pricing rules | One tiny condition used once |
| Shipping logic | Hard-coded behavior that never changes |
| Recommendation ranking | Extremely simple procedural scripts |
| Fraud-scoring policies | Problems with no interchangeable behavior |
Mini Quiz¶
What stays stable in the Strategy Pattern?
What changes from one strategy to another?
What is the biggest practical benefit of Strategy in business apps?
Answer Check
The context object
The algorithm or decision rule
It allows business logic to evolve without rewriting the whole workflow
Practice Prompt¶
Build a ShippingStrategy system with StandardShipping, ExpressShipping, and PickupShipping.
Design Hint
Keep the order-processing workflow inside one context class, and move only shipping-cost computation into the strategy classes.
Interactive Code¶
What to notice
The workflow still runs through the same Checkout class. Only the policy-selection step changes which strategy gets injected.
Guided Practice¶
Which design choice best signals a Strategy pattern?¶
Exercises¶
Add a
HolidayShippingstrategy that applies a time-limited discount.Refactor a long
if/elifdecision tree into small strategy classes.
Exercise hint
Define a common cost() method first, then make the calculator depend only on that interface rather than on concrete shipping types.
Key Takeaway¶
Strategy helps you say: same workflow, different policy.
Quick Exercise Solution Hint¶
HolidayShippingabove shows a ready implementation for Exercise 1 in the practice prompt. Try replacing the placeholder strategy withHolidayShipping()in the practice cell to verify behavior.