调用 new 和 getInstance() 的区别 [英] Difference between calling new and getInstance()

查看:27
本文介绍了调用 new 和 getInstance() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用 Class.getInstance() 是否等同于 new Class()?我知道构造函数是为后者调用的,但是 getInstance() 呢?谢谢.

Is calling Class.getInstance() equivalent to new Class()? I know the constructor is called for the latter, but what about getInstance()? Thanks.

推荐答案

没有Class#getInstance()这样的方法.您可能将它与 Class#newInstance().是的,这与 default 构造函数上的 new 完全相同.这是其 Javadoc<的摘录/a>:

There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:

创建由这个 Class 对象表示的类的新实例.该类被实例化,就像通过一个带有空参数列表的 new 表达式一样.如果该类尚未初始化,则该类会被初始化.

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

在代码中,

Object instance = Object.class.newInstance();

Object instance = new Object();

Class#newInstance() 调用实际上遵循 工厂方法 模式.

The Class#newInstance() call actually follows the Factory Method pattern.

更新:看到其他答案,我意识到您的问题有些含糊不清.嗯,实际上一个名为 getInstance() 的方法被使用的地方通常表示一个 抽象工厂 模式.它将在引擎盖下"使用 newClass#newInstance() 创建并返回感兴趣的实例.只是为了隐藏你可能不需要知道的关于具体实现的所有细节.

Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.

此外,您还经常在 Singleton 模式.

Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.

这篇关于调用 new 和 getInstance() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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