Strategy Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
Intent & Objective
Let the algorithm vary independently from clients that use it by packaging business rules into separate strategy objects conforming to a common interface.
"You decide whether to walk, drive, bike, or take a bus depending on weather, traffic, and urgency without changing your destination."
"Bake, fry, boil, or steam the same raw vegetable or cut of meat depending on the desired texture and flavor."
"Interchangeable payment algorithms (Credit Card, PayPal, Crypto, Cash on Delivery) selected dynamically at checkout."
"A tech lead chooses daily focus strategy: addressing critical bug fixes, accelerating feature development, or refactoring technical debt."
The Problem
Giant monolithic methods filled with 200 lines of `if (routeType == WALKING) { ... } else if (routeType == BICYCLE) { ... }`. Modifying one algorithm risks breaking all the others.
The Solution
Extract each algorithm into a separate class implementing a common Strategy interface. The Context holds a reference to a Strategy and delegates execution.
Key Participants & Architectural Roles
Code Samples (Traditional OOP vs Functional Programming)
Available in C++, Python, and JavaParadigm Contrast: Traditional OOP vs Functional / Data-Oriented
In OOP, Strategy requires an interface and multiple strategy classes. In Functional Programming, Strategy is the most trivial and natural pattern: simply pass a first-class function (lambda or callback) as a regular argument!
Advantages
- ✓ Swaps algorithms at runtime dynamically
- ✓ Isolates algorithmic implementation details from code that uses them
- ✓ Replaces inheritance and switch statements with clean composition (Open/Closed Principle)
Trade-offs
- ✗ Clients must be aware of the differences between strategies to select the right one
When to Apply
- → When you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime
- → When you have a lot of similar classes that only differ in the way they execute some behavior
When to Avoid
- ! When you only have a single algorithm that never changes