【JDK 8-函数式编程】4.4 Supplier

一、Supplier 接口

二、实战

Stage 1: 创建 Student 类

Stage 2: 创建方法

Stage 3: 调用方法

Stage 4: 执行结果


一、Supplier 接口

  • 供给型 接口: 无入参,有返回值(T : 出参类型)

  • 调用方法: T get();

  • 用途: 如 无参的工厂方法,即工厂设计模式创建对象,简单来说就是 提供者

/**
 * * @param <T> the type of results supplied by this supplier
 */
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

二、实战

Stage 1: 创建 Student 类

public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Stage 2: 创建方法

    public static Student newStudent() {
        Supplier<Student> supplier = () -> {
            Student student = new Student();
            student.setName("默认名称");
            return student;
        };
        return supplier.get();
    }

Stage 3: 调用方法

    public static void main(String[] args) {

        Student student = newStudent();
        log.info(student.getName());
    }

Stage 4: 执行结果

猜你喜欢

转载自blog.csdn.net/ladymorgana/article/details/132986316
今日推荐