An example of the strategy design pattern
Let's see an example of how to use the strategy design pattern to sort a collection of objects. Suppose you have a class called Product that represents a product with attributes such as name, price, and rating. You want to sort a list of products by different criteria, such as by name, by price, or by rating. You can use the strategy design pattern to define a family of sorting algorithms that can be applied to the list of products.
First, you need to define a strategy interface that declares a method to sort a list of products. For example:
public interface SortStrategy {
void sort(List<Product> products);
}
Next, you need to implement concrete strategy classes that inherit from the strategy interface and provide different sorting algorithms. For example:
public class SortByName implements SortStrategy {
@Override
public void sort(List<Product> products) {
// Sort products by name using some algorithm
}
}
public class SortByPrice implements SortStrategy {
@Override
public void sort(List<Product> products) {
// Sort products by price using some algorithm
}
}
public class SortByRating implements SortStrategy {
@Override
public void sort(List<Product> products) {
// Sort products by rating using some algorithm
}
}
Then, you need to define a context class that holds a reference to a strategy object and provides a method to set or change the strategy at runtime. For example:
public class ProductSorter {
private SortStrategy strategy;
public void setStrategy(SortStrategy strategy) {
this.strategy = strategy;
}
public void sort(List<Product> products) {
strategy.sort(products);
}
}
Finally, you can use the context class to invoke the strategy method and execute the sorting algorithm. For example:
public class Main {
public static void main(String[] args) {
List<Product> products = ...; // Create a list of products
ProductSorter sorter = new ProductSorter(); // Create a context object
sorter.setStrategy(new SortByName()); // Set the strategy to sort by name
sorter.sort(products); // Sort the products by name
sorter.setStrategy(new SortByPrice()); // Set the strategy to sort by price
sorter.sort(products); // Sort the products by price
sorter.setStrategy(new SortByRating()); // Set the strategy to sort by rating
sorter.sort(products); // Sort the products by rating
}
}