Supplier JAVA,在Java中使用Supplier有什么好处?

Supplier JAVA,在Java中使用Supplier有什么好处?ReadingaboutthenewSupplierinterfaceIcan’tseeanyadvantageofitsusage.Wecanseebellowanexampleofit.classVehicle{publicvoiddrive(){System.out.println(“Drivingvehicle…”);}}classC…

Supplier JAVA,在Java中使用Supplier有什么好处?

Reading about the new Supplier interface I can’t see any advantage of its usage.

We can see bellow an example of it.

class Vehicle{

public void drive(){

System.out.println(“Driving vehicle …”);

}

}

class Car extends Vehicle{

@Override

public void drive(){

System.out.println(“Driving car…”);

}

}

public class SupplierDemo {

static void driveVehicle(Supplier extends Vehicle> supplier){

Vehicle vehicle = supplier.get();

vehicle.drive();

}

}

public static void main(String[] args) {

//Using Lambda expression

driveVehicle(()-> new Vehicle());

driveVehicle(()-> new Car());

}

As we can see in that example, the driveVehicle method expects a Supplier as argument.

Why don’t we just change it to expect a Vehicle?

public class SupplierDemo {

static void driveVehicle(Vehicle vehicle){

vehicle.drive();

}

}

public static void main(String[] args) {

//Using Lambda expression

driveVehicle(new Vehicle());

driveVehicle(new Car());

}

What is the advantage of using Supplier?

EDIT: The answers on the question Java 8 Supplier & Consumer explanation for the layperson doesn’t explain the benefits of using Supplier.

There is a comment asking about it, but it wasn’t answered.

What is the benefit of this rather than calling the method directly?

Is it because the Supplier can act like an intermediary and hand off

that “return” value?

解决方案

In your example above I’d not use a supplier. You are taking a Vehicle to drive, not requesting vehicles.

However to answer your general question:

Because building a car is expensive and we don’t want to do it until we really really need to.

Because we want X cars not just one.

Because the time of construction for a car is important.

Because construction is complicated so we want to wrap it up.

Because we don’t know which Vehicle to return until we return it (maybe it will be a new one, maybe a recycled one, maybe a wrapper, who knows)

今天的文章Supplier JAVA,在Java中使用Supplier有什么好处?分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/9693.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注