Java Reference
In-Depth Information
method with values such as a String, an Integer, or a boolean. This can be fine for certain
well-defined problems. But in this case what you need is a better way to tell your filterApples
method the selection criteria for apples. In the next section we describe how to make use of
behavior parameterization to attain that flexibility.
2.2. Behavior parameterization
You saw in the previous section that you need a better way than adding lots of parameters to
cope with changing requirements. Let's step back and find a better level of abstraction. One
possible solution is to model your selection criteria: you're working with apples and returning a
boolean based on some attributes of Apple (for example, is it green? is it heavier than 150 g?).
We call this a predicate (that is, a function that returns a boolean). Let's therefore define an
interface to model the selection criteria :
public interface ApplePredicate{
boolean test (Apple apple);
}
You can now declare multiple implementations of ApplePredicate to represent different
selection criteria, for example (and illustrated in figure 2.1 ) :
Figure 2.1. Different strategies for selecting an Apple
 
Search WWH ::




Custom Search