Java8--行为参数化

行为参数化,是我在《Java 8 实战》中学到的。下面举一个例子来说明什么是行为参数化。

现在要写一个过滤器对所有的苹果按照不同条件进行过滤:

  • 苹果实体类如下
public class Apple {
    private String color;
    private double weight;
    public Apple(String color, double weight) {
        this.color = color;
        this.weight = weight;
    }
    public String getColor() {
        return this.color;
    }
    public double getWeight() {
        return this.weight;
    }
    @Override
    public String toString() {
        return "color: " + this.color + ", weight: " + this.weight;
    }
}
public interface ApplePredicate {
    boolean test(Apple apple);
}
  • 测试类
public class Test {
    public static void main(String[] args) {
        Test t = new Test();
        List<Apple> aList = Arrays.asList(new Apple("red",3.4),
                new Apple("green",3.5),
                new Apple("red",4.2));
        // 无需去写接口的实现类,使用Lambda表达式即将整个方法作为参数传递,也就是行为参数化
        // 下面我用两种策略去过滤苹果,却都只需一行代码
        List<Apple> list1 = t.filterApples(aList, (a) -> a.getColor().equals("red") && a.getWeight() > 3.5);
        List<Apple> list2 = t.filterApples(aList, (a) -> a.getColor().equals("green"));
        System.out.println(list1);
        System.out.println(list2);
    }
    // 实现苹果的过滤
    public List<Apple> filterApples(List<Apple> aList,ApplePredicate predicate){
        List<Apple> list = new ArrayList<>();
        for(Apple a : aList) {
            if(predicate.test(a))
                list.add(a);
        }
        return list;
    }
}

其实我们之前使用匿名类也就是这里所说的行为参数化,不过我们现在使用Lambda表达式更简洁。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章