简体   繁体   English

为什么要使用getInstance

[英]why use getInstance

A lot of the publicly available Java APIs seem to use getInstance in order to generate and return an object. 很多公开的Java API似乎都使用getInstance来生成和返回一个对象。 I'm curious about why this is so -- why not just use default/parameterized constructors instead? 我很好奇为什么会这样 - 为什么不使用默认/参数化构造函数呢?

Is there an associated design pattern? 是否有相关的设计模式?

I suggest to read "Effective Java" by Joshua Bloch, Item 1 "Consider static factory methods instead of constructors". 我建议阅读Joshua Bloch撰写的“Effective Java”,第1项“考虑静态工厂方法而不是构造函数”。 He led the design and implementation of numerous Java platform features, he knows why. 他领导了众多Java平台功能的设计和实现,他知道为什么。

It is associated with Singleton Pattern . 它与Singleton Pattern相关联。

Many times there are also Factory Methods which help you in creating objects. 很多时候,还有工厂方法可以帮助您创建对象。

For example: Boolean.parseBoolean("true"); 例如: Boolean.parseBoolean("true");

Advantages of Factory Methods are they are more verbose and easy to grasp than a series of constructors. 工厂方法的优点是它们比一系列构造函数更加冗长和易于掌握。

Another example (apart from the singleton or multi-ton pattern) is if you need to do something in the constructor that is generally not recommended, such as registering a listener or starting a thread: 另一个例子(除了单例或多吨模式)是你需要在构造函数中做一些通常不推荐的事情,比如注册一个监听器或启动一个线程:

class Whatever {

    private Whatever() {} //private constructor
    public Whatever getInstance() {
        Whatever w = new Whatever();
        startSomeThread();
        return w;
    }
}

Yes....It is associated with both Factory and Singleton pattern. 是的....它与Factory和Singleton模式相关联。 Factory pattern is used to decouple the object creation logic from the business logic and Singleton pattern is used to maintain only a single instance of an object through out the application. 工厂模式用于将对象创建逻辑与业务逻辑分离,而Singleton模式用于在整个应用程序中仅维护对象的单个实例。

To save you the trouble of looking up concrete reasons... 为了省去查找具体原因的麻烦......

This is a case of the Factory Method pattern. 这是Factory Method模式的一种情况。 The most common reasons to use it are: 使用它的最常见原因是:

  1. If construction is too complex to handle in a constructor 如果构造太复杂而无法在构造函数中处理
  2. If construction requires actions that are not permitted or desired in a constructor 如果构造需要构造函数中不允许或不需要的操作
  3. To decouple the type of the product ("interface") from the actual implementation ("class"). 将产品类型(“接口”)与实际实现(“类”)分离。
  4. For performance or architechtural reasons, such as to perform partial specialization at construction time 出于性能或架构原因,例如在施工时执行部分专业化
  5. For clarity/readability 为了清晰/可读性

There is some overlap between these reasons. 这些原因之间存在一些重叠。 In fact, often all four apply. 事实上,通常所有四个都适用。 Partial specialization (4) pretty much requires decoupling of type and implementation (3). 部分特化(4)几乎需要解耦类型和实现(3)。

"why not just use default/parameterized constructors instead" because at the point you invoke the constructor it is already too late to ensure the Singleton Pattern constraint to have only one instance. “为什么不只是使用默认/参数化构造函数”,因为在调用构造函数 ,确保Singleton Pattern约束只有一个实例已经太晚了。 The whole point is to have controlled access to a single instance and avoid multiple instances. 重点是对单个实例进行受控访问并避免多个实例。 The only way to do that is to use access modifiers to prevent the constructor from being accessible. 唯一的方法是使用访问修饰符来防止构造函数被访问。

As it has been said, it's a matter of some pattern designs "requirements" to provide an easy/secure solution. 如上所述,提供简单/安全的解决方案是一些模式设计“要求”的问题。

But you should avoid the using of "getInstance" (java.lang.Class.getInstance()' and 'java.lang.Class.NewInstance()') as far as possible in terms of Dynamic Instantiation , because Dynamic instantiation is slower than a regular Class invocation or Method call. 但是你应该尽可能避免在动态实例化方面使用“getInstance”(java.lang.Class.getInstance()'和'java.lang.Class.NewInstance()'),因为动态实例化比常规的类调用或方法调用。

Use it only when it is necessary! 仅在必要时使用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我没有 InputManager.getInstance()? 和注入输入事件()? - Why is there no InputManager.getInstance() for me? And injectInputEvent()? 为什么Factory模式中的getInstance()方法是静态的? - Why should the getInstance() method in Factory pattern be static? 当getInstance方法不是静态的时,为什么会引发stackOverflowError - Why it throws stackOverflowError when the getInstance method is not static 为什么在单例getInstance中getApplicationContext抛出nullPointerException? - Why is getApplicationContext throwing nullPointerException, in singleton getInstance? 如何将Calendar.getInstance与指定的Locale一起使用 - How to use Calendar.getInstance with specified Locale 如何使用 FirebaseInstanceId.getInstance().deleteInstanceId()? - How to use FirebaseInstanceId.getInstance().deleteInstanceId()? 何时使用构造函数,何时使用 getInstance() 方法(静态工厂方法)? - When to use a Constructor and when to use getInstance() method (static factory methods)? 为什么我的 Singleton.getInstance() 不在 android 中执行? - Why isn't my Singleton.getInstance() executing in android? 为什么 bean 'reactorServiceInstanceLoadBalancer' 仅在调用方法 'getInstance' 时实例化? - Why is the bean 'reactorServiceInstanceLoadBalancer' instantiated just when the method 'getInstance' is called? 为什么在TestExecutionListener的beforeTestClass和afterTestClass方法中,TestContext.getInstance()为null? - Why is TestContext.getInstance() is null in beforeTestClass and afterTestClass methods in TestExecutionListener?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM