patterntypescriptTip
Strategy Pattern: Select Algorithms at Runtime
Viewed 0 times
strategy patternbehavioral patternalgorithm selectionruntime switchinginject strategyfunction injection
Problem
A class has behavior that varies depending on context (sorting algorithm, payment method, compression codec) and you want to switch between variants without conditionals scattered through the class.
Solution
Define a strategy interface. Implement each algorithm as a separate strategy class. Inject the chosen strategy into the context via constructor or setter.
interface SortStrategy<T> {
sort(data: T[]): T[];
}
class BubbleSort<T> implements SortStrategy<T> {
sort(data: T[]): T[] {
const arr = [...data];
// bubble sort implementation
return arr;
}
}
class QuickSort<T> implements SortStrategy<T> {
sort(data: T[]): T[] {
const arr = [...data];
// quicksort implementation
return arr;
}
}
class DataProcessor<T> {
constructor(private strategy: SortStrategy<T>) {}
setStrategy(strategy: SortStrategy<T>): void {
this.strategy = strategy;
}
process(data: T[]): T[] {
return this.strategy.sort(data);
}
}
const processor = new DataProcessor(new QuickSort<number>());
processor.process([3, 1, 4, 1, 5]);
// switch to bubble sort for small arrays
processor.setStrategy(new BubbleSort<number>());Why
Strategy eliminates branching on type in the context class (no
if payload.type === 'paypal'), keeps each algorithm isolated and testable, and enables runtime switching.Gotchas
- In TypeScript/JavaScript, plain functions often replace strategy classes for simple cases: pass a sort function instead of a SortStrategy object.
- Strategies should be stateless when possible. Stateful strategies complicate reuse and sharing.
- Clients must be aware of available strategies to choose one — this can be a coupling if strategies are not well-documented.
Revisions (0)
No revisions yet.