java - 在 Java 中使用 Supplier 有什么优势?

标签 java java-8

阅读新的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/

相关文章:

java-8 - Lambda 表达式测验

java - 在 DB 与内存中搜索数据时的性能

java - 导入 com.google.cloud.backend.R;丢失的

r - 在 java Eclipse 中使用 JRI 时如何导入 R 库?

java - JDK8 CompletableFuture.supplyAsync如何处理interruptedException

java - 在java流中重写算法更省力?

java - 即使 GPS 提供商可用,也不会调用 onLocationChanged

java - JAX-RS 中的社交身份验证

Instant.EPOCH 的 Java 8 时区不正确

java - 使用 Collectors.groupingBy() 时获取 map 的值集