阅读新的Supplier
界面我看不出它的使用有任何优势。
我们可以在下面看到一个例子。
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());
}
正如我们在该示例中所见,driveVehicle
方法需要一个 Supplier
作为参数。
为什么我们不直接将其更改为期待 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());
}
使用 Supplier
有什么好处?
编辑: Java 8 Supplier & Consumer explanation for the layperson 问题的答案没有解释使用 Supplier
的好处。
有评论询问,但没有得到答复。
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?
最佳答案
在您上面的示例中,我不会使用供应商。您正在驾驶 Vehicle
驾驶,而不是请求车辆。
但是回答你的一般问题:
- 因为造车成本高昂,除非真正需要,否则我们不想造车。
- 因为我们想要 X 辆车,而不仅仅是一辆。
- 因为制造汽车的时间很重要。
- 因为施工复杂,所以我们想把它包起来。
- 因为在我们归还它之前我们不知道要归还哪个 Vehicle(也许是新的,也许是回收的,也许是 wrapper ,谁知道呢)
关于java - 在 Java 中使用 Supplier 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960921/