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 filterHeavyApples(List inventory){
List result = new ArrayList<>();
for (Apple apple: inventory){
if (apple.getWeight() > 150) {
result.add(apple);
}
}
return result;
}那么,现在丙、丁又分别提出了从苹果选取产自郑州、品种为红富士的需求,怎么办呢,继续写函数?如果又加了无尽的需求呢?是不是不利于代码的扩展性呢?那么以前人们在遇到这个问题时是怎么处理的呢?没错,用的就是策略模式,即设计一个接口,将接口的不同实现类的实例传入方法内,而这个接口就称为断言。具体看实例吧:interface ApplePredicate{
public boolean test(Apple a);
}
static classAppleWeightPredicate implementsApplePredicate{
public booleantest(Apple apple){
returnapple.getWeight() > 150;}
}
static classAppleColorPredicate implementsApplePredicate{
public booleantest(Apple apple){
return"green".equals(apple.getColor());}
}
public staticList filter(List inventory,ApplePredicate p){
List result = newArrayList<>();for(Apple apple : inventory){
if(p.test(apple)){
result.add(apple);}
}
returnresult;}
使用的方法如下:
// [Apple{color="green", weight=80}, Apple{color="green", weight=155}]List greenApples2 = filter(inventory, newAppleColorPredicate());System.out.println(greenApples2);// [Apple{color="green", weight=155}]List heavyApples = filter(inventory, newAppleWeightPredicate());System.out.println(heavyApples);怎么样,是不是将不同的部分抽象出来会使代码读起来更清晰,也更容易维护呢?