【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: 执行结果

相关推荐
lulu12165440781 分钟前
JetBrains IDE 终极AI编程方案:CC GUI插件让Claude Code和Codex丝滑运行
java·ide·人工智能·python·ai编程
('-')32 分钟前
八股复习2:Java Array list和Linked list
java·开发语言
小黄人软件41 分钟前
C++读写编辑CSV文件示例源码 用于数据导入导出,比Excel好使
开发语言·c++·excel
郭涤生1 小时前
C++各个版本的性能和安全性总结
开发语言·c++
逸Y 仙X1 小时前
Elasticsearch时间类型实战
java·大数据·elasticsearch·搜索引擎·全文检索
Gerardisite1 小时前
企微批量群发消息指南:用 QiWe 省掉人工操作
java·python·机器人·企业微信
wljy12 小时前
二、静态库的制作和使用
linux·c语言·开发语言·c++
道剑剑非道2 小时前
FFmpeg 6.0 实战:用 C++ 封装摄像头采集与 RTSP 推流
开发语言·c++·ffmpeg
天天进步20152 小时前
Python全栈项目实战:基于深度学习的语音合成(TTS)系统
开发语言·python·深度学习
OctShop大型商城源码3 小时前
.NET线上商城源码_C#商城源码_技术赋能下的电商新生态
开发语言·c#·.net·商城系统源码