开发者社区> 问答> 正文

[@talishboy][¥20]java中getInstance()和newInstance()的区别?

java中getInstance()和newInstance()的区别?
摘一段《Effective Java》的代码,英文版第10页:
getInstance-Returns an instance that is described by the parameters but cannot be said to have the same http://value.In the case of a singleton,getInstance takes no parameters and returns the sole instance.

newInstance-Like getInstance,except that newInstance guarantees that each instance returned is distinct the from all others.
疑惑的是我看到的newInstance大都在单例中使用,对distinct the from all others不理解,我一直以为getInstance和newInstance都是在单例中使用,只是命名习惯不同而已,效果相同。照这里的意思,在这两个命名习惯上会区别对待?

展开
收起
月下丶 2018-12-14 22:30:11 2338 0
2 条回答
写回答
取消 提交回答
  • 我理解,getInstance是单例模式里获取单例的方法名称,你可以随意改。newInstance是java.lang.Class里的方法名,会调用构造方法构造新的实例。

    2019-07-17 23:21:41
    赞同 展开评论 打赏
  • 事实上,getInstance如果不传入参数,通常是我们在单例模式中使用的方式,如果传入参数,则对应多例模式。

    而newInstance,每次都会构造新的实例,你疑问的 distinct the from all others 指定是通过newInstance接口,每次返回的object的reference必须是不同的,因此,它返回的就是新的实例。

    2019-07-17 23:21:41
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载