在Java中是否有可能让构造函数返回该类的另一个实例,而不是构造/返回它自己?
有点像
public class Container {
private static Container cachedContainer = new Container(5,false);
private int number;
public Container(int number, boolean check) {
if (number == 5 && check) {
return cachedContainer; // <-- This wouldn't work
}
this.number = number;
}
}
Run Code Online (Sandbox Code Playgroud)
在该示例中,如果您创建一个包含数字5的对象(并使用"check"标志),它将"中断"构造,而是为您提供一个已经包含5的预先存在的对象.任何其他数字都不会导致中断.