简体   繁体   中英

What is the advantage of using Supplier in Java?

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

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

What is the advantage of using Supplier ?

EDIT: 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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