我有一个可以建造多种类型物体的工厂,它可能会增长。
使用反射返回所有不同类型而不是调用方法中的每个方法是个好主意getPrototypes()
吗?
反射看起来像这样:
public final class ShapeFactory
{
private ShapeFactory(){} // no instance
public static Shape buildSquare()
{
return new Square(2);
}
public static Shape buildCircle()
{
return new Circle(2);
}
public static Shape buildTriangle()
{
return new Triangle(2, 2, 2);
}
// and many more shapes...
public static List<Shape> getPrototypes()
{
final List<Shape> prototypes = new ArrayList<>();
// using reflection, call every build function
final Method[] methods = ShapeFactory.class.getMethods();
for(final Method picked : methods)
{
if(picked.getReturnType() == Shape.class && picked.getParameterTypes().length == 0)
{
try
{
prototypes.add((Shape)picked.invoke(null));
}
catch(final Exception e)
{
// this is an example, do not ignore
// exceptions in real code
}
}
}
return prototypes;
}
}
很抱歉使用 Shape 示例。
编辑:形状是可克隆的原型。编辑#2:改进示例以防有人使用它。