Java 8 新特性
行为参数化
// 行为参数化的一个直观的例子
// 需求:现在有一堆苹果,能根据不同的筛选条件来筛选苹果,比如根据颜色、大小、重量、品种、产地等
// 进行筛选,也可以根据他们的不同组合新型筛选
// 如何做?
public interface Predicate {
boolean test(Apple apple);
}
public class WeightPredicate implements Predicate {
public boolean test(Apple apple) {
return apple.getWeight() > 100;
}
}
public class ColorPredicate implements Predicate {
public boolean test(Apple apple) {
return "red".equals(apple.getColor());
}
}
List<Apple> filter(List<Apple> inventory, Predicate p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple) {
result.add(apple);
}
}
return result;
}
inventory = filter(inventory, new WeightPredicate());
inventory = filter(inventory, new ColorPredicate());
// 这里的 Predicate 就是对行为的抽象,比如过滤红色的、重量大于100g的等
// 通过将 Predicate 当作参数传给 filter 来实现筛选的能力
// 同时根据需要可以实现不同的 Predicate,来满足不同的功能
// 实际上是把筛选的逻辑的逻辑通过行为参数化了,这就是行为参数化Lambda
流
最后更新于