天天看点

【简化代码】Supplier接口实际运用

介绍

supplier接口是java.util.function下的一个用于返回对象的一个函数接口。源码如下:

【简化代码】Supplier接口实际运用

如源码所示它有几个特性

  • 主要用于返回结果
  • 支持函数编程
  • 调用get方法的时候才会创建对象返回(懒加载)

实际使用场景

我们在代码中,有时候会遇到一个通用方法,里面的有些逻辑在不同的地方有不同的实现,这时候入参可以使用Supplier,简化代码。栗子如下:

public static void main(String[] args) {
       System.out.println(commonMethod(doError1));
       System.out.println(commonMethod(doError2));
   }

   public static String  commonMethod(Supplier<String> doError){
       try {
           System.out.println("do Somthing");
           throw new Exception();
       } catch (Exception e) {
           log.error("error happen");
           return doError.get();
       }
   }

  private static Supplier<String> doError1 = () -> {
       System.out.println(" do error1");
       return "erro1";
   };

  private static Supplier<String> doError2 = () -> {
       System.out.println(" do error2");
       return "erro2";
   };
           

总结:在获取对象的时候,如工厂模式,通用方法,或者用到懒加载的地方的时候可以考虑使用Supplier接口简化代码,进行解耦。

多总结,多学习 这样就不用加晚班。