简体   繁体   English

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

[英]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: 但是要回答你的一般问题:

  • 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. 因为我们希望X车不只是一辆。
  • 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) 因为在返回之前我们不知道要返回哪辆车(也许它会是新车,也许是回收车,也许是包装纸,谁知道)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM