第二节:行为参数化

2018-06-18  本文已影响0人  monkeyzi

行为参数化可以这样理解:就是拿出一个代码块,把它准备好却不去执行他,这个代码块在以后可以被你程序的其他部分调用,也就是说你可以推迟代码的执行。例如:你可以将代码块最为参数传递给另一个方法,稍后再去执行它,这样,这个方法的行为就基于那块代码参数化了!

新建一个Apple类

public class Apple {
private String color;
private Integer weight;
//省略getter setter
}

图解:多个行为,一个参数

参数行为化.png

图1:参数化filterApple的行为并传递不同的筛选策略

代码:行为参数化,用谓词筛选苹果

// 新建一个接口
public interface ApplePredicate<T> {
        boolean filter(T t);
        }
//创建类实现filter(T t)这个方法
  //筛选重的苹果的条件
public class GetWeightApple implements ApplePredicate{
 public boolean filter(Apple apple){
    return apple.getWeight()>150;
 }
 }
//筛选绿色苹果的条件
public class GetGreenApple implements ApplePredicate{
 public boolean filter(Apple apple){
    return "green".equals(apple.getColor());
 }
 }
   //将删选的结果放入集合中
public static List<Apple> filterApple(List<Apple> apples,ApplePredicate p){
    List<Apple> list=new ArrayList<>();
    for(Apple apple:apples){
        if(p.filter(apple)){
            list.add(apple);
        }
    }
    return  list;
}

  //测试结果
 public  static void main(String[] args){
   List<Apple> list= Arrays.asList(
           new Apple("green",29),
           new Apple("red",245),
           new Apple("red",34));
  List<Apple> heavyList=filterApple(list,new GetWeightApple());
  System.out.println(heavyList);

  List<Apple> greenList=filterApple(list,new GetGreenApple())
   System.out.println(greenList);
}

我们能看出,虽然使用了参数行为化的手段,但是写的代码量是有点多的,但是,来理解行为参数化,对于我们看源码以及平时编码有很大的帮助,下面我们就用lambda表达式来实现一下,暂时了解一下lambda表达式。

lambda表达式,筛选出绿色的苹果

List<Apple> greenList=filterApple(list,(Apple,apple)->"green".equals(apple.getColor());

lambda表达式实现筛选出重的苹果

 List<Apple> weightList=filterApple(list,(Apple,apple)->apple.getWeight()>150);

这样的代码就比以前干净了很多,但是有些人还是觉得,代码有点多,别急,后续章节会讲到的!
如有不正确的对方,请指出!qq:854152531@qq.com

上一篇下一篇

猜你喜欢

热点阅读