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

[一、Supplier 接口](#一、Supplier 接口)

二、实战

[Stage 1: 创建 Student 类](#Stage 1: 创建 Student 类)

[Stage 2: 创建方法](#Stage 2: 创建方法)

[Stage 3: 调用方法](#Stage 3: 调用方法)

[Stage 4: 执行结果](#Stage 4: 执行结果)


一、Supplier 接口

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

  • 调用方法: T get();

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

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

二、实战

Stage 1: 创建 Student 类

java 复制代码
public class Student {
    private String name;

    public String getName() {
        return name;
    }

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

Stage 2: 创建方法

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

Stage 3: 调用方法

java 复制代码
    public static void main(String[] args) {

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

Stage 4: 执行结果

相关推荐
Chen_harmony3 小时前
十六、ALV树
开发语言·c++
qq_274475153 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
西西弗Sisyphus4 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 初识回调(5)
开发语言·c++
程序员小杰@4 小时前
Java 统一报文转换 + 签名验签完整介绍
java·开发语言
小张成长计划..4 小时前
【Linux】44:五种IO模型与非阻塞IO
java·服务器·数据库
不甘平凡的小鸟4 小时前
vs code 打开spring boot项目
java·spring boot·后端
ZhengEnCi4 小时前
Java 内存泄漏怎么排查:jstat、heap dump 与 MAT 线上定位流程
java·jvm·性能优化
Java后端的Ai之路5 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
船神丿男人5 小时前
从爬楼梯到最小路径和:6 道 C++ 动态规划题的状态设计
开发语言·c++·动态规划
Evand J5 小时前
【MATLAB例程】基于多基站AOA与距离辅助的二维运动目标定位及速度估计,附下载链接
开发语言·matlab·距离·aoa·多基站