我使用 Factory Pattern (工厂模式)在运行时初始化新实例。
问题:哪个版本最快? Java 12是否有更好的模式或解决方案?
/**
* VERSION 1:
*
* Uses Reflection with clazz
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(Class<T> colorClass) {
T t = null;
try {
t = colorClass.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* VERSION 2:
*
* Uses Reflection with canonical name of class
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(String colorClassName) {
T red = null;
try {
red = (Color) Class.forName(colorClassName).getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return red;
}
/**
* VERSION 3: (abstract factory pattern?)
*
* Uses switch without reflection
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(ColorName colorName) {
T t = null;
switch (colorName) {
case red:
return new Red();
break;
case green:
return new Green();
break;
case blue:
return new Blue();
break;
case black:
return new Black();
break;
default:
break;
}
return t;
}
根据建议,我包括了版本4(这似乎是最好的解决方案!):
public enum ColorName {
Red(ColorRed.class),
Green(ColorGreen.class),
Blue(ColorBlue.class),
Black(ColorBlack.class);
ColorName(Class<?> clazz) {
this.clazz = clazz;
}
private final Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public Color createColor() {
Color c = null;
try {
c = (Color) this.clazz.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}