1. 程式人生 > >java8之行為引數化(一)

java8之行為引數化(一)

  現在,我們有一個需求,甲希望從一堆蘋果中選出顏色是綠色的,乙希望從一堆蘋果中選出重量大於150的,程式碼該怎麼實現呢?按照我們的思路一起來:
  public static List<Apple> filterGreenApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if ("green".equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }

    public static List<Apple> filterHeavyApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if (apple.getWeight() > 150) {
                result.add(apple);
            }
        }
        return result;
    }
   那麼,現在丙、丁又分別提出了從蘋果選取產自鄭州、品種為紅富士的需求,怎麼辦呢,繼續寫函式?如果又加了無盡的需求呢?是不是不利於程式碼的擴充套件性呢?那麼以前人們在
遇到這個問題時是怎麼處理的呢?沒錯,用的就是策略模式,即設計一個介面,將介面的不同實現類的例項傳入方法內,而這個介面就稱為斷言。具體看例項吧:
interface ApplePredicate{
		public boolean test(Apple a);
	}

static class AppleWeightPredicate implements ApplePredicate{
   public boolean 
test(Apple apple){ return apple.getWeight() > 150; } } static class AppleColorPredicate implements ApplePredicate{ public boolean test(Apple apple){ return "green".equals(apple.getColor()); } }
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){
   List<Apple> result = new 
ArrayList<>(); for(Apple apple : inventory){ if(p.test(apple)){ result.add(apple); } } return result; }
使用的方法如下:
 
 
// [Apple{color='green', weight=80}, Apple{color='green', weight=155}]
List<Apple> greenApples2 = filter(inventory, new AppleColorPredicate());
System.out.println(greenApples2);

// [Apple{color='green', weight=155}]
List<Apple> heavyApples = filter(inventory, new AppleWeightPredicate());
System.out.println(heavyApples);
怎麼樣,是不是將不同的部分抽象出來會使程式碼讀起來更清晰,也更容易維護呢?