Java Reference
In-Depth Information
8.2.1. Strategy
The strategy pattern is a common solution for representing a family of algorithms and letting
you choose among them at runtime. You briefly saw this pattern in chapter 2 , when we showed
you how to filter an inventory with different predicates (for example, heavy apples or green
apples). You can apply this pattern to a multitude of scenarios, such as validating an input with
different criteria, using different ways of parsing, or formatting an input.
The strategy pattern consists of three parts, as illustrated in figure 8.1 :
Figure 8.1. The strategy design pattern
An interface to represent some algorithm (the interface Strategy )
One or more concrete implementations of that interface to represent multiple algorithms (the
concrete classes ConcreteStrategyA , ConcreteStrategyB )
One or more clients that use the strategy objects
Let's say you'd like to validate whether a text input is properly formatted for different criteria
(for example, it consists of only lowercase letters or is numeric). You start by defining an
interface to validate the text (represented as a String):
public interface ValidationStrategy {
boolean execute(String s);
}
Second, you define one or more implementation(s) of that interface:
public class IsAllLowerCase implements ValidationStrategy {
public boolean execute(String s){
return s.matches("[a-z]+");
}
}
 
Search WWH ::




Custom Search