1、初试牛刀:筛选绿苹果

第一个解决方案可能是下面这样的:

 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;
    }

2、再展身手:把颜色作为参数

public static List<Apple> filterGreenApples(List<Apple> inventory,String color){
        List<Apple> result=new ArrayList<>();
        //颜色作为参数
        for (Apple apple : inventory) {
            if (color.equals(apple.getColor())){
                result.add(apple);
            }
        }
        return result;
    }

3、第三次尝试:对你能想到的每个属性做筛选

   public static List<Apple> filterGreenApples(List<Apple> inventory,String color,int weight,boolean flag){
        List<Apple> result=new ArrayList<>();
        for (Apple apple : inventory) {
            if (flag && color.equals(apple.getColor())|| (!flag && apple.getWeight()>weight)){
                result.add(apple);
            }
        }
        return result;
    }

4、柳暗花明:行为参数化

//封装了对选择苹果的策略
public interface ApplePredicate {

    //具体算法交给子类去实现
    boolean test (Apple apple);
}
//颜色算法
public class AppleGreenColorPredicate implements  ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return "green".equals(apple.getColor());
    }
}
//重量算法
public class AppleHeavyWeightPredicate implements  ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return apple.getWeight()>150;
    }
}

5、第四次尝试:根据抽象条件筛选

   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> heavyApples = filterApples(inventory, new AppleHeavyWeightPredicate());
List<Apple> greenApples = filterApples(inventory, new AppleGreenColorPredicate());

6、第五次尝试:使用匿名类

 List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
            @Override
            public boolean test(Apple apple){
            return "red".equals(apple.getColor());
            }
        });

7、第六次尝试:使用Lambda表达式

List<Apple>result= filterApples(inventory, (Apple apple)-> "red".equals(apple.getColor()));

8、第七次尝试:将List类型抽象化

public interface Predicate<T> {
    boolean test(T 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;
    }

9、小结

04-06 04:36