Java Reference
In-Depth Information
Bingo! You're now able to pass multiple behaviors to your prettyPrintApple method. You do this
by instantiating implementations of AppleFormatter and giving them as arguments to
prettyPrintApple:
prettyPrintApple(inventory, new AppleFancyFormatter());
This will produce an output along the lines of
A light green apple
A heavy red apple
...
Or try this:
prettyPrintApple(inventory, new AppleSimpleFormatter());
This will produce an output along the lines of
An apple of 80g
An apple of 155g
...
You've seen that you can abstract over behavior and make your code adapt to requirement
changes, but the process is verbose because you need to declare multiple classes that you
instantiate only once. Let's see how to improve that.
2.3. Tackling verbosity
We all know that a feature or concept that's cumbersome to use will be avoided. At the moment,
when you want to pass new behavior to your filterApples method, you're forced to declare
several classes that implement the ApplePredicate interface and then instantiate several
ApplePredicate objects that you allocate only once, as shown in the following listing that
summarizes what you've seen so far. There's a lot of verbosity involved and it's a
time-consuming process!
Search WWH ::




Custom Search