说我有一个Car抽象类:
public abstract class Car {
public enum Feature {
FAST, SEXY, RELIABLE, FUEL_EFFICIENT
};
public static List<Feature> getFeatures() {
return new ArrayList<Car.Feature>();
}
public abstract int getMaxSpeed();
}
以及许多具有各种构造函数的Car实现,如下这两个:
public class CarA extends Car {
private static List<Feature> features = Arrays.asList(new Feature[] {
Feature.FAST, Feature.SEXY });
private int maxSpeed;
public CarA(int year) {
maxSpeed = year > 2000 ? 240 : 220;
}
public static List<Feature> getFeatures() {
return features;
}
@Override
public int getMaxSpeed() {
return maxSpeed;
}
}
和
public class CarB extends Car {
private static List<Feature> features = Arrays
.asList(new Feature[] { Feature.FAST });
private int maxSpeed;
public CarB(int year, int modelNumber) {
if (modelNumber > 10) {
maxSpeed = year > 2010 ? 180 : 160;
} else {
maxSpeed = 100;
}
}
public static List<Feature> getFeatures() {
return features;
}
@Override
public int getMaxSpeed() {
return maxSpeed;
}
}
我想写一个汽车类工厂,根据人的品味建议一些具有不同配置的汽车实例:
public class CarFactory {
public static class UserPreferences {
public List<Feature> requiredFeatures;
public int minimumSpeed;
}
public List<Car> getMatchingCars(int year, UserPreferences preferences) {
List<Class<?>> candidateCarClasses = Arrays.asList(new Class<?>[] {
CarA.class, CarB.class });
List<Class<?>> carClassesWithIncorrectFeatures = new ArrayList<Class<?>>();
for (Class<?> candidateClass : candidateCarClasses) {
Class<Car> carClass = (Class<Car>) candidateClass;
// XXX how do I check carClass.getFeatures() are included in
// requiredFeatures? carClass.getMethod("getFeatures",null)???
}
candidateCarClasses.removeAll(carClassesWithIncorrectFeatures);
List<Car> cars = new ArrayList<Car>;
for (Class<?> candidateClass : candidateCarClasses) {
if (CarA.class.equals(candidateClass.getClass())) {
CarA carA = new CarA(year);
// the rest is easy...
} else if (...) {
// the rest is easy...
}
}
return cars;
}
}
我的问题是:
如何访问各种汽车类的静态方法,而无需在代码中的位置XXX实例化任何汽车对象?
如果无法做到或者我没有正确接近,那么解决问题的正确方法是什么?即在必须实例化剩下的候选类之前,我的汽车工厂如何能够首先修剪所有没有正确功能的类。 (在我考虑的实际情况中,我有很多对象实例要考虑每个类,构造函数是资源密集型的。)
显然,我可以将每个汽车实现所支持的功能移到一个单独的地图中,但似乎更清晰的方法是将所有信息与该实现中的特定汽车实例相关,而不是分散在多个位置。