在Java中,构造函数是否可以返回该类的另一个实例,而不是构造/返回自身? [英] Is it possible in Java to have a constructor return another instance of the class, rather than constructing/returning itself?

查看:49
本文介绍了在Java中,构造函数是否可以返回该类的另一个实例,而不是构造/返回自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否可以让构造函数返回该类的另一个实例,而不是构造/返回自身?

Is it possible in Java to have a constructor return another instance of the class, rather than constructing/returning itself?

像金达一样

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;
    }
}

在该示例中,如果您创建一个包含数字5的对象(并使用"check"标志),它将中断"该构造,而是为您提供一个已经包含5的预先存在的对象.不会造成这种干扰.

In that example, if you create an object containing the number 5 (and use the "check" flag), it will "interrupt" the construction and instead give you a preexisting object that already contains 5. Any other number won't cause such interruption.

推荐答案

没有,这就是静态工厂方法的地方模式进来

您可以执行自定义计算并确定是否以静态工厂方法创建实例

You could perform custom calculation and determine whether to create instance or not in static factory method

请考虑以下示例:

public static Container createContainer(int number, boolean check) {
    if (number == 5 && check) {
      // returned cached instance
    }
    // construct new instance and return it
}

来自有效的Java

项目1:考虑使用静态工厂方法而不是构造函数

摘要:

  • 可以使用名称与客户进行清晰的沟通
  • 您可以执行自定义逻辑,而不必每次都创建实例
  • 您可以返回子类型

另请参见

这篇关于在Java中,构造函数是否可以返回该类的另一个实例,而不是构造/返回自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆