行为参数化

2021-09-06  本文已影响0人  JESiller
图片.png

以筛选绿色苹果为例,展示行为参数化的渐进过程,代码更加简洁,功能更易于扩展。

 public static List<Apple> filterGreenApples(List<Apple> inventory) {
        List<Apple> result = new ArrayList<Apple>();
        for (Apple apple : inventory) {
            if ("green".equals(apple.getColor()) {
                result.add(apple);
            }
        }
        return result;
    }
 public static List<Apple> filterApplesByColor(List<Apple> inventory,
                                                  String color) {
        List<Apple> result = new ArrayList<Apple>();
        for (Apple apple : inventory) {
            if (apple.getColor().equals(color)) {
                result.add(apple);
            }
        }
        return result;
    }
 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() {
        public boolean test(Apple apple) {
            return "green".equals(apple.getColor());
        }
    });
List<Apple> result = 
 filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));
上一篇下一篇

猜你喜欢

热点阅读