gpt4 book ai didi

java - 调用 new 和 getInstance() 的区别

转载 作者:太空狗 更新时间:2023-10-29 23:01:08 26 4
gpt4 key购买 nike

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

最佳答案

没有 Class#getInstance() 这样的方法。您可能将它与 Class#newInstance() 混淆了.是的,这与 default 构造函数中的 new 完全相同。这是其 Javadoc 的摘录:

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() 调用实际上遵循 Factory Method模式。


更新:看到其他答案,我意识到你的问题有些含糊不清。好吧,实际上名为 getInstance() 的方法被使用的地方通常表示一个 Abstract Factory。图案。它将“在幕后”使用 newClass#newInstance() 创建并返回感兴趣的实例。它只是为了隐藏您可能不需要了解的有关具体实现的所有细节。

此外,您还经常在 Singleton 的某些(主要是本土开发的)实现中看到此方法名称。模式。

另见:

关于java - 调用 new 和 getInstance() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3170159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com