【Java8 新特性 3】Supplier简介,java视频直播技术架构

Supplier persionSupplier = Person::new;

Arrays.asList(“a”,“b”,“c”).forEach(e->System.out.println(e));

在Java8中增加的接口Supplier,最适合用于表示工厂。带有Supplier的方法,通常应该限制输入工厂的类型参数使用有限制的通配符类型,以便客户端能够传入一个工厂,来创建指定类型的任意子类型。

应该将这些资源或者工厂传给构造器(或者静态工厂、或者构建器),通过他们来创建类。这个实践就被称做依赖注入,它极大地提高了类的灵活性、可重用性和可测试性。

简而言之,Supplier就是用来创建对象的,相当于new。

2、代码实例

package com.guor.effective.chapter2.java8;

import java.util.function.Supplier;

public class TestSupplier {

private int age;

public static void test(){

System.out.println(“Java8新特性,Supplier”);

}

TestSupplier(){

System.out.println(“构造函数,age,”+age);

}

public static void main(String[] args) {

//创建Supplier容器,声明为TestSupplier类型,此时并不会调用对象的构造方法,即不会创建对象

Supplier sup= TestSupplier::new;

sup.get().test();

System.out.println("--------");

//调用get()方法,此时会调用对象的构造方法,即获得到真正对象

sup.get();

//每次get

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

都会调用构造方法,即获取的对象不同

System.out.println(“是否是相同的对象实例”+sup.get()==sup.get().toString());

}

}

3、控制台输出

4、通俗易懂

private static int getMax(Supplier supplier) {

return supplier.get();

}

private static void test01() {

Integer[] arr = {10,2,5,3,9,4};

int max2 = getMax(() -> {

int max = 0;

for(Integer i : arr) {

if(i > max) {

max = i;

}

}

return max;

});

System.out.println(max2);//10

}

二、Supplier源码分析


Supplier接口源码中只有一个get()方法。

每次get都会调用构造方法,即获取的对象不同。

/*

  • Copyright © 2012, 2013, Oracle and/or its affiliates. All rights reserved.

  • ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.

*/

package java.util.function;

/**

  • Represents a supplier of results.

  • There is no requirement that a new or distinct result be returned each

  • time the supplier is invoked.

  • This is a functional interface

  • whose functional method is {@link #get()}.

  • @param the type of results supplied by this supplier

  • @since 1.8

*/

@FunctionalInterface

public interface Supplier {

/**

  • Gets a result.

  • @return a result

*/

T get();

}

可以看到这份代码中,有一个比较奇特的注解@FunctionalInterface,这是一个函数式接口的声明。该注解不是必须的,如果一个接口符合"函数式接口"定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错。

三、lambda表达式与Supplier的组合使用


为何不直接使用new?而使用Supplier,感觉华而不实,和new有啥区别?

1、person类

package com.guor.effective.chapter2.java8;

public class Person {

Integer id;

String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

你可能感兴趣的:(程序员,面试,java,后端)