行为参数化
public interface ApplePredicate<T> {
boolean test(T t);
}
public class AppleWeightPredicate implements ApplePredicate<Apple>{
public boolean test(Apple apple){
return apple.getWeight() > 150;
}
}
public class AppleColorPredicate implements ApplePredicate<Apple>{
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}
//传递代码
// filter方法的行为取决于ApplePredicate对象传递的代码,也就是方法的行为参数化
public static<T> List<T> filter(List<T>inventory, ApplePredicate<T> p){
List<T> result = new ArrayList<>();
for(T t : inventory){
if(p.test(t)){
result.add(t);
}
}
return result;
}
List<Apple> heavyApples = filter(inventory, new AppleWeightPredicate());
List<Apple> greenApples2 = filter(inventory, new AppleColorPredicate());
// 匿名类方式
List<Apple> redApples2 = filter(inventory, new ApplePredicate() {
public boolean test(Apple a){
return a.getColor().equals("red");
}
});
//Lambda表达式
List<Apple> greenApples3 = filter(inventory, apple -> "green".equals(apple.getColor()));
List<Apple> heavyApples3 = filter(inventory, apple -> apple.getWeight() > 150);