鉴于以下情况:
public interface Vehicle {
// Makes this vehicle race another Vehicle and returns who wins the race.
public Vehicle race(Vehicle otherVehicle);
}
public class Car implements Vehicle {
@Override
public Vehicle race(Vehicle otherVehicle) {
// Different algorithms are used to determine who wins based on
// what type otherVehicle is.
if(otherVehicle instanceof Car) {
// Use algorithm #1 to determine who wins the race
} else if(otherVehicle instanceof Helicopter) {
// Use algorithm #2 to determine who wins the race
} else if(otherVehicle instanceof Motorcycle) {
// Use algorithm #3 to determine who wins the race
}
// ...etc.
}
}
public class Helicopter implement Vehicle {
@Override
public Vehicle race(Vehicle otherVehicle) {
// Same problem as above with Car.
}
}
public class Motorcycle implements Vehicle {
// ... same problem here
}
... lots of other types of Vehicles
由于使用不同的算法来比较 Car
与 Car
、Car
与 Helicopter
等,因此 race(Vehicle)
方法的实现变得难看,并且充满了 instanceof
检查......恶心。
必须有一种更加面向对象的方式来做到这一点......想法吗?
最佳答案
您可以使用double dispatch图案:
public interface Vehicle {
// Makes this vehicle race another Vehicle and returns who wins the race.
public Vehicle race(Vehicle otherVehicle);
public Vehicle race(Helicopter otherVehicle);
public Vehicle race(Motorcycle otherVehicle);
public Vehicle race(Car otherVehicle);
}
public class Helicopter implement Vehicle {
@Override
public Vehicle race(Vehicle otherVehicle) {
otherVehicle.race(this);
}
public Vehicle race(Helicopter heli) {
}
...
}
public class Car implement Vehicle {
@Override
public Vehicle race(Vehicle otherVehicle) {
otherVehicle.race(this);
}
public Vehicle race(Helicopter heli) {
return heli;
}
...
}
public static void Main(string args[]) {
Vehicle car = new Car();
Vehicle helicopter = new Helicopter();
Vehicle winner = helicopter.race(car);
// returns helicopter
}
关于java - 比较父类型的两个子类型时正确的 API 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448805/