在Java中使用Supplier有什么好处? [英] What is the advantage of using Supplier in Java?

查看:5934
本文介绍了在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());
}

正如我们在该示例中所见, driveVehicle 方法需要 Supplier 作为参数。
为什么我们不改变它以期望车辆

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());
}

使用供应商有什么好处? c $ c>?

What is the advantage of using Supplier?

编辑:问题的答案 Java 8 Supplier&消费者对非专业人士的解释并未解释使用供应商的好处。
有评论询问,但没有回答。

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:


  • 因为建造汽车很贵我们真的不需要这样做。

  • 因为我们想要 X 汽车而不仅仅是一辆汽车。

  • 因为建造汽车的时间很重要。

  • 因为施工很复杂所以我们想把它包起来。

  • 因为我们不知道返回哪辆车(也许它会是新车,也许是回收车,也许是包装纸,谁知道)

  • 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)

这篇关于在Java中使用Supplier有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆