Java Reference
In-Depth Information
}
}
Answer:
First, you need a way to represent a behavior that takes an Apple and returns a formatted String
result. You did something similar when you created an ApplePredicate interface:
public interface AppleFormatter{
String accept(Apple a);
}
You can now represent multiple formatting behaviors by implementing the Apple-Formatter
interface:
public class AppleFancyFormatter implements AppleFormatter{
public String accept(Apple apple){
String characteristic = apple.getWeight() > 150 ? "heavy" : "light";
return "A " + characteristic +
" " + apple.getColor() +" apple";
}
}
public class AppleSimpleFormatter implements AppleFormatter{
public String accept(Apple apple){
return "An apple of " + apple.getWeight() + "g";
}
}
Finally, you need to tell your prettyPrintApple method to take AppleFormatter objects and use
them internally. You can do this by adding a parameter to prettyPrintApple:
public static void prettyPrintApple(List<Apple> inventory,
AppleFormatter formatter){
for(Apple apple: inventory){
String output = formatter.accept(apple);
System.out.println(output);
}
}
 
Search WWH ::




Custom Search