Java Reference
In-Depth Information
You can see these criteria as different behaviors for the filter method. What you just did is
related to the strategy design pattern,
[
1
]
which lets you define a family of algorithms, encapsulate
each algorithm (called a strategy), and select an algorithm at run-time. In this case the family of
algorithms is ApplePredicate and the different strategies are AppleHeavyWeightPredicate and
AppleGreenColorPredicate.
But how can you make use of the different implementations of ApplePredicate? You need your
filterApples method to accept ApplePredicate objects to test a condition on an Apple. This is
what
behavior parameterization
means: the ability to tell a method to
take
multiple behaviors
(or strategies) as parameters and use them internally to
accomplish
different behaviors.
To achieve this in the running example, you add a parameter to the filterApples method to take
an ApplePredicate object. This has a great software engineering benefit: you can now separate
the logic of iterating the collection inside the filterApples method with the behavior you want to
apply to each element of the collection (in this case a predicate).
2.2.1. Fourth attempt: filtering by abstract criteria
Our modified filter method, which uses an ApplePredicate, looks like this:
Search WWH ::
Custom Search