Strategy
Define a family of interchangeable algorithms, each in its own class β swap them at runtime without changing the code that uses them.
Intent & Description
π― Intent
Extract varying algorithms into separate classes so they can be selected, swapped, and extended independently of the code that uses them.
π Context
Your sorting function needs to be pluggable (quicksort vs. mergesort vs. timsort). Your navigation app needs to switch between road, walking, and cycling routes. Your payment processor needs to handle credit card, PayPal, and crypto. Hardcoding these switches creates conditional sprawl.
π‘ Solution
Define a Strategy interface. Implement each algorithm as a concrete Strategy class. A Context object holds a reference to the current Strategy and delegates the algorithm call. Client code sets the Strategy; the Context executes it.
Real-world Use Case
Source
π TL;DR
Algorithm = its own class. Swap at runtime via the Context. Each strategy is isolated and testable. Don’t bother if you have two variants that never change.
Advantages
- Swap algorithms at runtime β the Context doesn’t care which one is active.
- Each algorithm is isolated and independently testable.
- New strategies plug in without touching the Context or other strategies.
Disadvantages
- Unnecessary complexity if you only have two algorithms that never change.
class NavigationStrategy {
buildRoute(a, b) {}
}
class RoadStrategy extends NavigationStrategy {
buildRoute(a, b) { return `Road route from ${a} to ${b}`; }
}
class WalkingStrategy extends NavigationStrategy {
buildRoute(a, b) { return `Walking route from ${a} to ${b}`; }
}
class Navigator {
setStrategy(strategy) { this.strategy = strategy; }
buildRoute(a, b) { return this.strategy.buildRoute(a, b); }
}