Enhancing Code Flexibility with the Strategy Design Pattern
The Problem :
Consider a scenario where a developer needs to implement three sorting algorithms: Bubble Sort, Merge Sort, and Quick Sort. Without employing the Strategy Design Pattern
pubic class BubbleSort
public void sort(int[] arr)
{
//implementation of Bubble Sort
}
}
pubic class MergeSort{
public void sort(int[] arr)
{
//implementation of Merge Sort
}
}
pubic class QuickSort{
public void sort(int[] arr)
{
//implementation of Quick Sort
}
}
public class Sorter {
private BubbleSort bubbleSort;
private MergeSort mergeSort;
private QuickSort quickSort;
public Sorter() {
bubbleSort = new BubbleSort();
mergeSort = new MergeSort();
quickSort = new QuickSort();
}
public void sortUsingBubbleSort(int[] arr) {
bubbleSort.sort(arr);
}
public void sortUsingMergeSort(int[] arr) {
mergeSort.sort(arr);
}
public void sortUsingQuickSort(int[] arr) {
quickSort.sort(arr);
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {3, 2, 4, 5, 1, 0, 6};
Sorter sorter = new Sorter();
sorter.sortUsingBubbleSort(arr);
sorter.sortUsingMergeSort(arr);
sorter.sortUsingQuickSort(arr);
}
}
{
Issues :
Recommended by LinkedIn
Solution :
public interface sortStrategy
void sort(int arr[]);
}
public class BubbleSort implements sortStrategy{
@Override
void sort(int arr[]){
//implement bubble sort
}
}
public class MergeSort implements sortStrategy{
@Override
void sort(int arr[]){
//implement Merge sort
}
}
public class QuickSort implements sortStrategy{
@Override
void sort(int arr[]){
//implement Quick sort
}
}
public class Sorter
{
private SortStrategy sortStrategy;
public void setSortStrategy(SortStrategy strategy)
{
this.sortStrategy=strategy;
}
public void sortArray(int []arr)
{
sorter.sort(arr);
}
}
public class Main{
public static void main(String[] args)
{
int[] arr={3,2,4,5,1,0,6};
Sorter sorter=new Sorter();
sorter.setSortStrategy(new BubbleSort());
sorter.sortArray(arr);
sorter.setSortStrategy(new MergeSort());
sorter.sortArray(arr);
sorter.setSortStrategy(new QuickSort());
sorter.sortArray(arr);
}
}
Advantages of Strategy Design Pattern :
Conclusion :
The Strategy Design Pattern is a powerful tool for achieving flexibility and maintainability in software development. By encapsulating algorithms in separate classes and selecting them dynamically through interfaces, we can significantly improve code organization and reusability. As we have seen through our example, the Strategy Design Pattern enhances code quality, adheres to design principles, and ultimately leads to more efficient, adaptable, and elegant solutions.