Java 8 Supplier 使用

在Java 8, Supplier是一個(gè)函數(shù)接口,它沒有參數(shù),返回了一個(gè)T.查了下字典,supplier被翻譯成"供應(yīng)商",那么它到底供應(yīng)了啥呢,從代碼上看,就是供應(yīng)了一個(gè)任意對(duì)象T唄,下面我們?nèi)タ纯磶讉€(gè)DEMO吧.

思考: 寫JDK代碼的大神們,為什么取名叫Supplier?為啥不叫Vendor或者Provider呢...我想了很久.

package java.util.function;

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

1、使用Supplier打印字符串

package com.cattles.function;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;

/**
 * @author cattle -  稻草鳥人
 * @date 2020/3/22 下午12:56
 */
public class Java8Supplier1 {

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        // print simple string
        Supplier<String> supplier = () -> "cattle";
        System.out.println(supplier.get());
        // print date time
        Supplier<LocalDateTime> time = () -> LocalDateTime.now();
        System.out.println(time.get());

        
        Supplier<String> s = () -> dtf.format(time.get());
        System.out.println(s.get());
    }
}

輸出:

cattle
2020-03-22T13:45:53.926364
2020-03-22 13:45:53

2、返回一個(gè)Supplier

下面我們創(chuàng)建一個(gè)簡(jiǎn)單的工廠方法返回一個(gè)Developer 對(duì)象

package com.cattles.function;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * @author cattle -  稻草鳥人
 * @date 2020/3/22 下午12:56
 */
public class Java8Supplier3 {


    public static void main(String[] args) {
        Developer developer = factory(Developer::new);
        System.out.println(developer);

        Developer developer1 = factory(()-> new Developer("tony"));
        System.out.println(developer1);

    }

    public static Developer factory(Supplier<? extends  Developer> supplier) {
        Developer developer = supplier.get();
        if(Optional.ofNullable(developer.getName()).isEmpty()) {
            developer.setName("cattle");
        }
        //可憐的人啊,薪水是zero
        developer.setSalary(BigDecimal.ZERO);
        //沒日沒夜干活的碼農(nóng)啊
        developer.setTitle("Coder");
        return developer;
    }


    static class Developer {
        /**
         * 姓名
         */
        private String name;
        /**
         * 職位
         */
        private String title;
        /**
         * 薪水
         */
        private BigDecimal salary;

        public Developer(String name) {
            this.name = name;
        }

        // 省略 gettter setter toString 方法
    }
}

看看結(jié)果:

Developer{name='cattle', title='Coder', salary=0}
Developer{name='tony', title='Coder', salary=0}
快上車,教你開車
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容