Intermediate Topic 24 of 50 Software Engineering
Strategy Pattern
Swapping interchangeable algorithms at runtime.
How it works
The strategy pattern defines a family of interchangeable algorithms behind a common interface and lets the client choose or swap one at run time. The context holds a reference to a strategy and delegates work to it, so behavior varies without conditional statements. In languages with first-class functions, a strategy can simply be a function passed in.
Step-by-step walkthrough
- The context holds a reference to a strategy.
- Each algorithm implements the same interface.
- The context calls the interface method.
- It can switch strategies at runtime.
- Behavior changes without if/else chains.
Where it is used
Choosing a sorting comparator, payment method, compression algorithm, pricing rule, routing algorithm or validation rule uses strategy. It supports the open-closed principle by adding new strategies without changing the context.
Common pitfall
Too many tiny strategy classes can be overkill for simple branching. Clients must know enough to pick the right strategy. All strategies must honor the same interface contract. If strategies share a lot of code, extract common logic. Use it when you have multiple variations of the same task that change independently.
Where it fits in the course
Strategy Pattern is topic 24 of 50 in Software Engineering, rated Intermediate. It follows Observer Pattern. The next topic is Decorator Pattern.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Software Engineering quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Software Engineering quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Strategy Pattern?
Where do people use Strategy Pattern?
What is the most common mistake with Strategy Pattern?
What should I learn before this topic?
How can I practice it?
Is Strategy Pattern hard to learn?
How long does it take to learn Strategy Pattern?
Which topics are related to Strategy Pattern?
What should I study after Strategy Pattern?
Related topics
- Observer Pattern (Software Engineering)
- Decorator Pattern (Software Engineering)
- Factory Pattern (Software Engineering)
- Dependency Injection (Software Engineering)
- Producer-Consumer Pattern (Concurrency & Parallelism)
- Saga Pattern (Distributed Systems & Cloud)
- Pattern Matching (Languages & Compilers)