java8之行为参数化(一)

  现在,我们有一个需求,甲希望从一堆苹果中选出颜色是绿色的,乙希望从一堆苹果中选出重量大于150的,代码该怎么实现呢?按照我们的思路一起来:
  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;
    }

    public static List<Apple> filterHeavyApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if (apple.getWeight() > 150) {
                result.add(apple);
            }
        }
        return result;
    }
   那么,现在丙、丁又分别提出了从苹果选取产自郑州、品种为红富士的需求,怎么办呢,继续写函数?如果又加了无尽的需求呢?是不是不利于代码的扩展性呢?那么以前人们在
遇到这个问题时是怎么处理的呢?没错,用的就是策略模式,即设计一个接口,将接口的不同实现类的实例传入方法内,而这个接口就称为断言。具体看实例吧:
interface ApplePredicate{
		public boolean test(Apple a);
	}

static class AppleWeightPredicate implements ApplePredicate{
   public boolean test(Apple apple){
      return apple.getWeight() > 150; 
   }
}
static class AppleColorPredicate implements ApplePredicate{
   public boolean test(Apple apple){
      return "green".equals(apple.getColor());
   }
}
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){
   List<Apple> result = new ArrayList<>();
   for(Apple apple : inventory){
      if(p.test(apple)){
         result.add(apple);
      }
   }
   return result;
} 
使用的方法如下:
 
 
// [Apple{color='green', weight=80}, Apple{color='green', weight=155}]
List<Apple> greenApples2 = filter(inventory, new AppleColorPredicate());
System.out.println(greenApples2);

// [Apple{color='green', weight=155}]
List<Apple> heavyApples = filter(inventory, new AppleWeightPredicate());
System.out.println(heavyApples);
怎么样,是不是将不同的部分抽象出来会使代码读起来更清晰,也更容易维护呢?
 
 
 
 

猜你喜欢

转载自blog.csdn.net/bird_one/article/details/78218809
今日推荐