Strategy pattern
Quality Score
Overall Score: 8.8/10 ✅ Excellent
- Technical Accuracy: 31/35
- Code Quality: 23/25
- Educational Value: 21/25
- Documentation: 13/15
Last reviewed: June 26, 2026
The strategy pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it, enabling selection at runtime without modifying client code. The main use case to implement this pattern is when you have multiple algorithms for a specific task and want to switch between them at runtime. Main benefits of this pattern are:
- Eliminates conditional logic: Replace if/else chains with polymorphism
- Encapsulation: Each algorithm is self-contained and easier to test
- Flexibility: Add new strategies without modifying existing code
- Runtime switching: Change behavior dynamically based on context
- Open/Closed Principle: Open for extension, closed for modification
The strategy pattern is composed of three main components:
Strategy Interface
Defines the common interface for all supported algorithms. The responsibility is to know how to execute, not when to use the strategy.
src.advanced.strategy_pattern.GreetingStrategy
Bases: ABC
Abstract base class for greeting strategies.
Source code in src/advanced/strategy_pattern/strategy.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Concrete Strategies
Implement the specific algorithm to be used. Each concrete strategy encapsulates a different behavior.
src.advanced.strategy_pattern.EnglishGreeting
Bases: GreetingStrategy
Concrete strategy for English greeting.
Source code in src/advanced/strategy_pattern/strategy.py
52 53 54 55 56 57 58 59 60 61 62 63 64 | |
src.advanced.strategy_pattern.FrenchGreeting
Bases: GreetingStrategy
Concrete strategy for French greeting.
Source code in src/advanced/strategy_pattern/strategy.py
37 38 39 40 41 42 43 44 45 46 47 48 49 | |
src.advanced.strategy_pattern.SpanishGreeting
Bases: GreetingStrategy
Concrete strategy for Spanish greeting.
Source code in src/advanced/strategy_pattern/strategy.py
22 23 24 25 26 27 28 29 30 31 32 33 34 | |
Context
Maintains a reference to a Strategy object to use and delegates algorithm execution to it.
src.advanced.strategy_pattern.GreetingProcessor
Context class that uses a greeting strategy given a person.
Source code in src/advanced/strategy_pattern/strategy.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
Some real-world examples are: payment processing, data compression, export formats, sorting algorithms, discount calculations...