在Java8中,Supplier
是一个函数式接口,它不接受任何参数,但是可以返回一个值。
Supplier.java
@FunctionalInterface
public interface Supplier<T> {
T get();
}
例子1: 基本用法
例子1演示的是通过Supplier
返回当前的时间。
Java8Supplier1.java
package cc.myexample;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;
public class Java8Supplier1 {
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
Supplier<LocalDateTime> s = () -> LocalDateTime.now();
LocalDateTime time = s.get();
System.out.println(time);
Supplier<String> s1 = () -> dtf.format(LocalDateTime.now());
String time2 = s1.get();
System.out.println(time2);
}
}
输出
2020-03-02T16:10:49.281223
2020-03-02 16:10:49
例子2: 返回一个Supplier
例子2演示的是一个通过Supplier
返回另一个Supplier
,达到工厂模式的效果。
Java8Supplier2.java
package cc.myexample;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Java8Supplier2<T> {
public static void main(String[] args) {
Java8Supplier2<String> obj = new Java8Supplier2<String>();
List<String> list = obj.supplier().get();
}
public Supplier<List<T>> supplier() {
// lambda表达式
// return () -> new ArrayList<>();
// 构造器引用
return ArrayList::new;
}
}
例子3: 工厂模式
例子3与例子2有点相似,它们都是通过Supplier
返回一个对象。
Java8Supplier3.java
package cc.myexample;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.function.Supplier;
public class Java8Supplier3<T> {
public static void main(String[] args) {
Developer obj = factory(Developer::new);
System.out.println(obj);
Developer obj2 = factory(() -> new Developer("myexample"));
System.out.println(obj2);
}
public static Developer factory(Supplier<? extends Developer> s) {
Developer developer = s.get();
if (developer.getName() == null || "".equals(developer.getName())) {
developer.setName("default");
}
developer.setSalary(BigDecimal.ONE);
developer.setStart(LocalDate.of(2017, 8, 8));
return developer;
}
}
Developer.java
package cc.myexample;
import java.math.BigDecimal;
import java.time.LocalDate;
public class Developer {
String name;
BigDecimal salary;
LocalDate start;
public Developer(String name) {
this.name = name;
}
// 省略get/set/构造器/toString
}
输出
Developer{name='default', salary=1, start=2017-08-08}
Developer{name='myexample', salary=1, start=2017-08-08}