【发布时间】:2013-12-08 01:27:56
【问题描述】:
鉴于以下情况:
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 vs. Car、Car vs Helicopter 等使用不同的算法,所以race(Vehicle) 方法的实现变得难看并且充满了instanceof 检查...哎呀.
必须有一种更面向对象的方式来做到这一点...想法?
【问题讨论】:
标签: java oop design-patterns inheritance instanceof