1.介绍
比如你有一个方法A,这个方法里面要处理一段的逻辑代码块m。这时又需要一个方法B,但是B方法去掉逻辑代码m不一样,其他与A方法完全相同,这时你需要把这段逻辑行为,当做参数来传递给一个综合方法C,用C方法来代替A,B方法。
例如这样把苹果的筛选条件抽出来
public interface ApplePredicate{
boolean test (Apple apple);
}
public class AppleHeavyWeightPredicate implements ApplePredicate{
public boolean test(Apple apple){
return apple.getWeight() > 150;
}
}
public class AppleGreenColorPredicate implements ApplePredicate{
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}
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;
}
代码很简单,但是还不够简洁,当然我们可以用内部类来做,省去两个接口的实现,但是还有更简单的方法,那就是Lambda语法啦(Java8)
List<Apple> result =
filterApples(inventory, (Apple apple) -> "red".equals(apple.getColor()));
List可以继续抽象,来实现所有Object
public interface Predicate<T>{
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p){
List<T> result = new ArrayList<>();
for(T e: list){
if(p.test(e)){
result.add(e);
}
}
return result;
}
到这里我们基本就很清楚行为参数化,以及如何来简化它了(学习Java8)