通過行為引數傳遞程式碼
阿新 • • 發佈:2019-01-13
一、概述
1.1、行為引數化的含義:讓方法接受多種行為作為引數,並在內部使用,來完成不同行為。 1.2、案例:我們要得到重量大於150克的蘋果和所有的綠蘋果。二、程式碼實現
2.1 行為引數化package com.jdk.test; public class Apple { private String color; private int weight; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Apple(String color, int weight) { super(); this.color = color; this.weight = weight; } @Override public String toString() { return "Apple [color=" + color + ", weight=" + weight + "]"; } }
package com.jdk.test;
/**
*
* @author Administrator
*策略模式的應用
*行為引數化:讓方法接受多種行為作為引數,並在內部使用,來完成不同的行為。
*/
public interface ApplePredicate {
boolean test(Apple apple);
}
package com.jdk.test; public class AppleGreenColorPredicate implements ApplePredicate { @Override public boolean test(Apple apple) { //選出綠色的蘋果 return "green".equals(apple.getColor()); } }
package com.jdk.test;
public class AppleHeavyWeightPredicate implements ApplePredicate {
@Override
public boolean test(Apple apple) {
//選出大於150克的蘋果
return apple.getWeight() > 150;
}
}
以上是我們使用行為引數化來實現的需求,下面我們來看下使用匿名內部類的實現方式:package com.jdk.test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FilteringApples { public static void main(String[] args) { List<Apple> inventory = Arrays.asList(new Apple("green",80), new Apple("red",190), new Apple("green",100)); List<Apple> heavryApples = filterApples(inventory,new AppleHeavyWeightPredicate()); heavryApples.forEach(Apple -> System.out.println("輸出重量大於150克"+Apple.toString())); List<Apple> greenApples = filterApples(inventory,new AppleGreenColorPredicate()); greenApples.forEach(Apple -> System.out.println("輸出綠色的Apple"+Apple.toString())); } public static List<Apple> filterApples(List<Apple> inventory,ApplePredicate p) { List<Apple> result=new ArrayList<>(); for (Apple apple : inventory) { if(p.test(apple)){ result.add(apple); } } return result; } }
List<Apple> redApples = filterApples(inventory,new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return "red".equals(apple.getColor());
}
});
redApples.forEach(Apple ->System.out.println("輸出紅色Apple"+Apple.toString()));
使用了匿名內部類並沒有讓我們感到程式碼的簡潔和易讀,我們再對上面的程式碼進行改造。
2.2使用Lambda表示式
List<Apple> greenApples = filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));
greenApples.forEach(Apple -> System.out.println("使用Lambda表示式"+Apple.toString()));
//按照大小升序排序
greenApples.sort((Apple a1,Apple a2) -> a1.getMax().compareTo(a2.getMax()));
這段程式碼看起來是不是清晰多了,這就是JDK8中的 Lambda表示式的寫法。
三、總結
通過上面的案例我們已經熟悉了JDK8中的Lambda表示式的寫法,我們可以將filter方法進行提取讓它變成一個公共 的程式碼塊,而不僅僅是過濾Apple了。public interface Predicate<T> {
boolean test(T t);
}
public static <T> List<T> filter(List<T> inventory,Predicate<T> p) {
List<T> result=new ArrayList<>();
for (T t : inventory) {
if(p.test(t)){
result.add(t);
}
}
return result;
}