gpt4 book ai didi

java - 在工厂中使用反射

转载 作者:行者123 更新时间:2023-11-29 09:04:41 25 4
gpt4 key购买 nike

我有一个工厂,可以构建多种类型的对象,并且它可能会增长。

使用反射返回所有不同的类型而不是调用 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 示例。

编辑:形状是可复制的原型(prototype)。编辑 #2:改进示例以防有人使用它。

最佳答案

Would it be a good idea to use reflection to return all the different types instead of calling every method in the getPrototypes() method?

这是一个合理的做法。反射代码更加复杂和脆弱,但这意味着您在添加新的形状构建器方法时无需更改 getPrototypes()。这取决于哪个对您更重要。

但是,您不应该像现在这样压缩异常。或许您应该更加谨慎地选择用于创建原型(prototype)的方法。 (如果您添加一个返回 Shape 但接受参数的方法......或者不是构建器,则当前版本将失败。)

关于java - 在工厂中使用反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15663819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com