Java 8 Supplier 使用
在Java 8, Supplier是一个函数接口,它没有参数,返回了一个T.查了下字典,supplier被翻译成"供应商",那么它到底供应了啥呢,从代码上看,就是供应了一个任意对象T呗,下面我们去看看几个DEMO吧.
思考: 写JDK代码的大神们,为什么取名叫Supplier?为啥不叫Vendor或者Provider呢...我想了很久.
1package java.util.function; 2 3@FunctionalInterface 4public interface Supplier<T> { 5 T get(); 6}
1、使用Supplier打印字符串
1package com.cattles.function; 2 3import java.time.LocalDateTime; 4import java.time.format.DateTimeFormatter; 5import java.util.function.Supplier; 6 7/** 8 * @author cattle - 稻草鸟人 9 * @date 2020/3/22 下午12:56 10 */ 11public class Java8Supplier1 { 12 13 private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 14 15 public static void main(String[] args) { 16 // print simple string 17 Supplier<String> supplier = () -> "cattle"; 18 System.out.println(supplier.get()); 19 // print date time 20 Supplier<LocalDateTime> time = () -> LocalDateTime.now(); 21 System.out.println(time.get()); 22 23 24 Supplier<String> s = () -> dtf.format(time.get()); 25 System.out.println(s.get()); 26 } 27} 28
输出:
1cattle 22020-03-22T13:45:53.926364 32020-03-22 13:45:53
2、返回一个Supplier
下面我们创建一个简单的工厂方法返回一个Developer 对象
1package com.cattles.function; 2 3import java.math.BigDecimal; 4import java.util.ArrayList; 5import java.util.List; 6import java.util.Optional; 7import java.util.function.Supplier; 8 9/** 10 * @author cattle - 稻草鸟人 11 * @date 2020/3/22 下午12:56 12 */ 13public class Java8Supplier3 { 14 15 16 public static void main(String[] args) { 17 Developer developer = factory(Developer::new); 18 System.out.println(developer); 19 20 Developer developer1 = factory(()-> new Developer("tony")); 21 System.out.println(developer1); 22 23 } 24 25 public static Developer factory(Supplier<? extends Developer> supplier) { 26 Developer developer = supplier.get(); 27 if(Optional.ofNullable(developer.getName()).isEmpty()) { 28 developer.setName("cattle"); 29 } 30 //可怜的人啊,薪水是zero 31 developer.setSalary(BigDecimal.ZERO); 32 //没日没夜干活的码农啊 33 developer.setTitle("Coder"); 34 return developer; 35 } 36 37 38 static class Developer { 39 /** 40 * 姓名 41 */ 42 private String name; 43 /** 44 * 职位 45 */ 46 private String title; 47 /** 48 * 薪水 49 */ 50 private BigDecimal salary; 51 52 public Developer(String name) { 53 this.name = name; 54 } 55 56 // 省略 gettter setter toString 方法 57 } 58} 59
看看结果:
1Developer{name='cattle', title='Coder', salary=0} 2Developer{name='tony', title='Coder', salary=0}
