[英]What is the advantage of using Supplier in Java?
Reading about the new Supplier
interface I can't see any advantage of its usage. 阅读有关新Supplier
界面的信息,我看不出其使用的任何优势。 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. 正如我们在该示例中所看到的, driveVehicle
方法需要将Supplier
作为参数。 Why don't we just change it to expect a Vehicle
? 为什么我们不改变它以期待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
? 使用Supplier
什么好处?
EDIT: The answers on the question Java 8 Supplier & Consumer explanation for the layperson doesn't explain the benefits of using Supplier
. 编辑:关于外行人Java 8供应商和消费者解释问题的答案并没有解释使用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. 您正在驾驶Vehicle
而不是请求车辆。
However to answer your general question: 但是要回答你的一般问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.