gpt4 book ai didi

java - 当对象是基类的实例时,为对象调用正确的方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:23:13 26 4
gpt4 key购买 nike

我在 Java 中有以下示例:

public abstract class Vehicle {
private final String name;
private final String make;

public Vehicle(final String name, final String make) {
this.make = make;
this.name = name;
}
}

public final class Car extends Vehicle {
public Car(final String name, final String make) {
super(name, make);
}
}

public final class Truck extends Vehicle {
final Integer grossVehicleWeight;

public Truck(final String name, final String make, final Integer gvw) {
super(name, make);
this.grossVehicleWeight = gvw;
}

假设我想用车辆做一些工作,而这项工作不依赖于车辆的子类。所以,我在另一个类中有一个这样的方法:

public void doStuff(public final Vehicle vehicle) {
//do stuff here
//then insert it into my database:
insertVehicle(vehicle);
}

但是,我想在我的 insertVehicle 中做不同的事情,所以我为每个子类覆盖了该方法:

public void insertVehicle(Car car) { //do stuff for a car }

public void insertVehicle(Truck truck) { //do stuff for a truck }

在我的 doStuff 方法中,我可以使用 instanceOf 来确定车辆的类(Car 或 Truck),然后将车辆转换为该类并调用 insertVehicle 方法,如下所示:

public void doStuff(public final Vehicle vehicle) {
//do stuff here
//then insert it into my database:
if (vehicle instanceof Car) {
insertVehicle((Car) vehicle);
} else {
insertVehicle((truck) vehicle);
}
}

但是,我了解到使用 instanceof 并不是执行此操作的最佳方法。 1

我怎样才能最好地修改它,以便我不必使用 instanceof?

最佳答案

您可以使用访问者模式:

public interface VehicleVisitor {
public void visit(Car car);
public void visit(Truck truck);
}

public class Car extends Vehicle {

@Override
public void insert(VehicleVisitor vehicleVisitor) {
vehicleVisitor.visit(this);
}
}

public class Truck extends Vehicle {
@Override
public void insert(VehicleVisitor vehicleVisitor) {
vehicleVisitor.visit(this);
}
}

public abstract class Vehicle {
public abstract void insert(VehicleVisitor vehicleVisitor);
}

public class VehicleVisitorImpl implements VehicleVisitor {

@Override
public void visit(Car car) {
System.out.println("insert car");
}

@Override
public void visit(Truck truck) {
System.out.println("insert truck");
}
}

public class Main {

public static void main(String[] args) {
Vehicle vehicle = new Car();
// finally the agnostic call
vehicle.insert(new VehicleVisitorImpl());
}

}

关于java - 当对象是基类的实例时,为对象调用正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com