在 Java 中使用 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());
}
正如我们在该示例中看到的,该方法需要一个 as 参数。我们为什么不直接将其更改为期望?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
与直接调用方法相比,这样做有什么好处?是因为供应商可以像中间人一样传递“回报”价值吗?