让我们说有人给你一个类Super,具有以下构造函数:
public class Super
{
public Super();
public Super(int arg);
public Super(String arg);
public Super(int[] arg);
}
Run Code Online (Sandbox Code Playgroud)
我们假设您要创建一个子类Derived.你如何有条件地调用构造函数Super?
换句话说,做出像这样的工作的"正确"方法是什么?
public class Derived extends Super
{
public Derived(int arg)
{
if (some_condition_1)
super();
else if (some_condition_2)
super("Hi!");
else if (some_condition_3)
super(new int[] { 5 });
else
super(arg);
}
}
Run Code Online (Sandbox Code Playgroud)
使用静态工厂和四个私有构造函数.
class Foo {
public static Foo makeFoo(arguments) {
if (whatever) {
return new Foo(args1);
} else if (something else) {
return new Foo(args2);
}
etc...
}
private Foo(constructor1) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
是的,@Johan Sj\xc3\xb6berg 说的。
\n\n看起来你的例子也是高度人为的。没有神奇的答案可以解决这个混乱:)
\n\n通常,如果您有这么多构造函数,最好将它们重构为四个单独的类(一个类应该只负责一种类型的事情)。
\n