strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
SKILL.mdskills/code-quality/strategy/SKILL.md
GitHubStrategy
Extracts algorithms into separate classes behind a common interface. The client/context picks a strategy at runtime without knowing implementation details.
When to Use
- Multiple variants of an algorithm exist and need to be swapped
- A class has a large conditional that selects algorithm variants
- Algorithm implementation details must be isolated from code that uses it
- Dependency injection of behaviour (sorting, pricing, routing, validation)
How to Apply
- Define a
Strategyinterface with the algorithm's method - Implement a concrete strategy class for each variant
- The
Contextclass holds aStrategyreference, injected via constructor or setter - Context delegates algorithm execution to the current strategy
- Client selects and injects the appropriate strategy
Example
interface SortStrategy { sort(data: number[]): number[]; }
class BubbleSort implements SortStrategy {
sort(data: number[]) { /* bubble sort */ return [...data].sort((a, b) => a - b); }
}
class QuickSort implements SortStrategy {
sort(data: number[]) { /* quick sort */ return [...data].sort((a, b) => a - b); }
}
class Sorter {
constructor(private strategy: SortStrategy) {}
setStrategy(s: SortStrategy) { this.strategy = s; }
sort(data: number[]) { return this.strategy.sort(data); }
}
const sorter = new Sorter(new BubbleSort());
sorter.sort([3, 1, 2]); // uses bubble sort
sorter.setStrategy(new QuickSort());
sorter.sort([30, 10, 20]); // uses quick sort