行为参数化
2021-09-06 本文已影响0人
JESiller

以筛选绿色苹果为例,展示行为参数化的渐进过程,代码更加简洁,功能更易于扩展。
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());
}
});
- Lambda表达式
List<Apple> result =
filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));