在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的预先存在的对象.任何其他数字都不会导致中断.
Jig*_*shi 15
不,这就是静态工厂方法模式的用武之地
您可以执行自定义计算并确定是否在静态工厂方法中创建实例
考虑这个例子:
public static Container createContainer(int number, boolean check) {
if (number == 5 && check) {
// returned cached instance
}
// construct new instance and return it
}
Run Code Online (Sandbox Code Playgroud)
从有效的java
第1项:考虑静态工厂方法而不是构造函数
摘要:
另见
好吧,这是不可能的,因为构造函数只是意味着为对象设置稳定状态,以后可以安全使用.简而言之,一旦初始化了对象,构造函数就可用于设置内部状态.所以返回任何东西毫无意义.
你真正可以做的是有一个公共静态方法,可以为你创建对象.就像是:
public class Container {
private static Container cachedContainer = new Container(5);
private int number;
public Container(int number) {
this.number = number;
}
public static Container getContainer(int number, boolean check){
if (number == 5 && check) {
return cachedContainer;
} else return new Container(number);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3858 次 |
| 最近记录: |