The Strategy Pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable at runtime. In this pattern, the algorithms can vary independently from the clients that use them.
Here’s an example of implementing the Strategy Pattern in Java:
Suppose we have a simple application that can sort a list of integers. We want to be able to choose different sorting algorithms at runtime. We’ll start by creating an interface that defines the sorting algorithm:
public interface SortingStrategy {
void sort(int[] array);
}
Next, we’ll create concrete classes that implement the SortingStrategy interface for different sorting algorithms:
public class QuickSort implements SortingStrategy {
@Override
public void sort(int[] array) {
// Implementation of quick sort algorithm
}
}
public class MergeSort implements SortingStrategy {
@Override
public void sort(int[] array) {
// Implementation of merge sort algorithm
}
}
Now, we’ll create a context class that will use the SortingStrategy:
public class SortContext {
private SortingStrategy sortingStrategy;
public void setSortingStrategy(SortingStrategy sortingStrategy) {
this.sortingStrategy = sortingStrategy;
}
public void sort(int[] array) {
sortingStrategy.sort(array);
}
}
In this example, the SortContext class holds a reference to a SortingStrategy. The setSortingStrategy method is used to set the current sorting strategy. The sort method is used to sort the array using the current sorting strategy.
Finally, we can use the SortContext class to sort our list of integers using different sorting algorithms:
int[] array = {3, 7, 1, 9, 4};
SortContext context = new SortContext();
// Sort using quick sort algorithm
context.setSortingStrategy(new QuickSort());
context.sort(array);
// Sort using merge sort algorithm
context.setSortingStrategy(new MergeSort());
context.sort(array);
In this example, we created an instance of the SortContext class and used it to sort an array of integers using different sorting algorithms at runtime. The SortingStrategy interface defines the common algorithm, and the concrete classes implementing this interface encapsulate the different sorting algorithms. The SortContext class encapsulates the selection of the sorting strategy, making the algorithm interchangeable at runtime.