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