行为参数化

图片.png

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

 public static List filterGreenApples(List inventory) {
        List result = new ArrayList();
        for (Apple apple : inventory) {
            if ("green".equals(apple.getColor()) {
                result.add(apple);
            }
        }
        return result;
    }
  • 值参数化
 public static List filterApplesByColor(List inventory,
                                                  String color) {
        List result = new ArrayList();
        for (Apple apple : inventory) {
            if (apple.getColor().equals(color)) {
                result.add(apple);
            }
        }
        return result;
    }
  • 实现接口类
 public static List filterApples(List inventory,
                                           ApplePredicate p) {
        List result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }
  • 匿名类
    List redApples = filterApples(inventory, new ApplePredicate() {
        public boolean test(Apple apple) {
            return "green".equals(apple.getColor());
        }
    });
  • Lambda表达式
List result = 
 filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));

你可能感兴趣的:(行为参数化)