Example of the strategy pattern
To illustrate how to apply the strategy pattern to diverse behaviors, let's consider a simple example of a data processing system. Suppose you have a class called DataProcessor, which takes a list of data items as input, and performs some operations on them, such as sorting, filtering, or validating. Depending on the type and format of the data, you may want to use different algorithms for each operation. For instance, you may want to sort the data by ascending or descending order, filter the data by some criteria, or validate the data by some rules.
To implement the strategy pattern, you need to define an interface for each operation, such as SortStrategy, FilterStrategy, or ValidateStrategy. Then, you need to create concrete classes that implement these interfaces, such as AscendingSortStrategy, DescendingSortStrategy, DateFilterStrategy, PriceFilterStrategy, EmailValidateStrategy, or PhoneValidateStrategy. These classes encapsulate the specific logic for each algorithm. Finally, you need to modify the DataProcessor class, so that it has a reference to each strategy interface, and a setter method to change them at runtime. For example:
class DataProcessor {
private SortStrategy sortStrategy;
private FilterStrategy filterStrategy;
private ValidateStrategy validateStrategy;
public DataProcessor(SortStrategy sortStrategy, FilterStrategy filterStrategy, ValidateStrategy validateStrategy) {
this.sortStrategy = sortStrategy;
this.filterStrategy = filterStrategy;
this.validateStrategy = validateStrategy;
}
public void setSortStrategy(SortStrategy sortStrategy) {
this.sortStrategy = sortStrategy;
}
public void setFilterStrategy(FilterStrategy filterStrategy) {
this.filterStrategy = filterStrategy;
}
public void setValidateStrategy(ValidateStrategy validateStrategy) {
this.validateStrategy = validateStrategy;
}
public void processData(List<DataItem> data) {
// sort the data using the sort strategy
sortStrategy.sort(data);
// filter the data using the filter strategy
data = filterStrategy.filter(data);
// validate the data using the validate strategy
validateStrategy.validate(data);
// do something with the processed data
// ...
}
}