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表達式更簡潔。

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