Published Apr 21, 2022
[
 
]
Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow. In order to tackle this we implemented Quick sort. But now although the quick sort algorithm was doing better for large datasets, it was very slow for smaller datasets. In order to handle this we implemented a strategy where for small datasets, bubble sort will be used and for larger, quick sort.
Strategy pattern allows you to switch the algorithm or strategy based upon the situation.
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables an algorithm’s behavior to be selected at runtime.
Translating our example from above. First of all we have our strategy interface and different strategy implementations
interface SortStrategy {
sort(dataset: number[]): number[];
}
class BubbleSortStrategy implements SortStrategy {
sort(dataset: number[]): number[] {
console.log('Sorting using bubble sort')
return dataset
}
}
class QuickSortStrategy implements SortStrategy {
sort(database: number[]): number[] {
console.log('Sorting using quick sort')
return database
}
}
And then we have our client that is going to use any strategy
class Sorter {
protected sorter;
constructor(sorter: SortStrategy) {
this.sorter = sorter
}
sort(dataset: number[]): number[] {
return this.sorter.sort(dataset)
}
}
And it can be used as
test('test strategy', () => {
const dataset = [1, 5, 4, 3, 2, 8]
let sorter = new Sorter(new BubbleSortStrategy())
sorter.sort(dataset)
sorter = new Sorter(new QuickSortStrategy())
sorter.sort(dataset)
})