JDK 新特性之 Supplier 生产器

Supplier 生产器

Supplier 源码

package java.util.function;

@FunctionalInterface
public interface Supplier<T> {
   T get();
}

Supplier 练习代码

import java.util.function.Supplier;
/**
 * 练习使用Supplier函数式接口
 */
public class UseSupplier {

    // 测试主函数
    public static void main(String[] args) {

        // 创建Supplier针对Person的生产器
        Supplier<UseSupplier.Person> personSupplier = UseSupplier.Person::new;

        // 使用Supplier生产器构建第一个Person实例,并初始化属性
        UseSupplier.Person person = personSupplier.get();
        person.setName("第一个实例");
        person.setAge(18);
        person.setSex("男");

        // 使用Supplier生产器构建第二个Person实例,并初始化属性
        UseSupplier.Person person1 = personSupplier.get();
        person1.setName("第二个实例");
        person1.setAge(20);
        person1.setSex("女");

        // 输出同一个Supplier生产器生产的两个实例person和person1,
        // 比较两个实例的属性是否一致,如果一致说明一个Supplier生产器只能生产一个实例,如果不一致说明一个Supplier可以生产多个实例
        System.out.println(person);
        System.out.println("比较两个实例属性是否一致 ---------------------->");
        System.out.println(person1);

        /**
         * 输出结果:
         *      Person{name='第一个实例', age=18, sex='男'}
         *      比较两个实例属性是否一致 ---------------------->
         *      Person{name='第二个实例', age=20, sex='女'}
         *
         * 结论:
         *      1、Supplier是一个函数式接口,只有一个get()方法
         *      2、Supplier不能使用有参构造,创建实例
         *      3、同一个生产器可以生产多个实例,👎每次调用get()方法都会生产一个新的实例
         * 语法:
         *      Supplier<T> supplier = T::new;      // 注意 T 必须有无参构造
         */
    }

    // 测试用类
    static class Person {
        private String name;

        private Integer age;

        private String sex;

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }

        public Person() {
        }

        public Person(String name, Integer age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值