JAVA8 Supplier<T> 接口

Supplier表示结果的提供者,不接受输入参数,只返回结果,是JDK 1.8 新增加的函数式接口

Supplier接口非常简单,只有一个get方法,只要实现这个接口的类都可以成为提供者。

@FunctionalInterface
public interface Supplier<T> {

    T get();
}

这么简单的方法有什么用呢?只要类似供应的场景就可以使用到。比如:榨汁机,需要供应原料,可以榨出想要的汁。

/**
 * 榨汁机
 */
public class Juicer {

    /**
     * 榨汁
     * @param rawMaterialSupplier 原材料供应
     * @param <T>
     * @return
     */
    public static  <T> Juice<T> juicing(Supplier<T> rawMaterialSupplier) {
        return new Juice<>(rawMaterialSupplier);
    }
}

/**
 * 榨汁机榨的汁
 */
public class Juice<T> {

    Supplier<T> supplier;

    Juice(Supplier<T> supplier){
        this.supplier = supplier;
    }

}

/**
 * 苹果
 */
public class Apple implements Supplier {
    @Override
    public Apple get() {
        return this;
    }
}


/**
 * 大豆
 */
public class Soybean implements Supplier {
    @Override
    public Soybean get() {
        return this;
    }
}

/**
 * @Author: swy
 * @Date: 2021/8/24 8:46
 */
public class SupplierDemo {

    public static void main(String[] args) {

        //榨苹果汁
        Juice<Apple> appleJuice = Juicer.juicing(new Apple());
        //榨豆浆
        Juice<Soybean> soybeanJuice = Juicer.juicing(new Soybean());
    }
}

再比如,一个人需要食物供应,对于一个苹果,可以直接吃,也可以榨苹果汁吃。那么榨苹果汁也可以成为供应者。

/**
 * 榨汁机榨的汁
 */
public class Juice<T> implements Supplier{

    Supplier<T> supplier;

    Juice(Supplier<T> supplier){
        this.supplier = supplier;
    }

    @Override
    public T get() {
        return supplier.get();
    }
}


/**
 * 人,做为食物的消费者,继承了Consumer接口
 */
public class People<T> implements Consumer<T> {
    public void eat(Supplier<T> supplier){
        accept(supplier.get());
    }
    public void drink(Supplier<T> supplier){
        accept(supplier.get());
    }

    @Override
    public void accept(T t) {
        System.out.println(t.getClass().getSimpleName());
    }
}


/**
 * @Author: swy
 * @Date: 2021/8/24 8:46
 */
public class SupplierDemo {

    public static void main(String[] args) {
        People people = new People();
        Apple apple = new Apple()

        //吃苹果
        people.eat(apple);

        //榨苹果汁
        Juice<Apple> appleJuice = Juicer.juicing(apple );

        //喝苹果汁
        people.drink(appleJuice);
    }
}

// 不管是直接吃,还是榨汁喝,最终都是吃了苹果
Apple
Apple

上面的两个例子,Supplier分别代表的原料和食物供应,可以说是原料和食物的抽象。虽然这样的抽象并不符合抽象的定义(比如:石头也可以实现Supplier成为食物),但在很多场合很有用。

了解了Supplier,其他的也就一目了然了:

LongSupplier:无参数,返回一个结果long类型的值

IntSupplier:无参数,返回一个int类型结果

DoubleSupplier:代表一个double值结构的提供方

BooleanSupplier:代表了boolean值结果的提供方

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值