Strategy design pattern best example
- Manbodh ratre
- Apr 17, 2024
- 1 min read
Updated: Jul 20, 2024
it allows to choose a algorithms from the family of algorithms
// Strategy Interface
interface SortingStrategy {
void sort(int[] arr);
}
// Concrete Strategies
class BubbleSort implements SortingStrategy {
public void sort(int[] arr) {
// Implementation of Bubble Sort algorithm
}
}
class MergeSort implements SortingStrategy {
public void sort(int[] arr) {
// Implementation of Merge Sort algorithm
}
}
class QuickSort implements SortingStrategy {
public void sort(int[] arr) {
// Implementation of Quick Sort algorithm
}
}
// Context
class Sorter {
private SortingStrategy strategy;
public Sorter(SortingStrategy strategy) {
this.strategy = strategy;
}
public void setStrategy(SortingStrategy strategy) {
this.strategy = strategy;
}
public void performSort(int[] arr) {
strategy.sort(arr);
}
}
// Usage
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 7, 1, 9, 3};
Sorter sorter = new Sorter(new BubbleSort()); // Initialize with Bubble Sort strategy
sorter.performSort(arr);
// Switch to Merge Sort strategy
sorter.setStrategy(new MergeSort());
sorter.performSort(arr);
// Switch to Quick Sort strategy
sorter.setStrategy(new QuickSort());
sorter.performSort(arr);
}
}
Comments