什么时候我们应该在Java中使用Singleton类? [英] When we should go for a Singleton class in Java?

查看:231
本文介绍了什么时候我们应该在Java中使用Singleton类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的想法,当我们在整个应用程序中共享相同的对象状态时,我们应该将类创建为Singleton。在这种情况下,我们希望用户每次都限制创建一个新实例,以便它们不能维持多个状态。同意。但是通过将实例变量声明为静态可以实现相同的行为。对我来说,无论是 cacheobjectcontainer logger 还是 Classloader,它看起来也会起到同样的作用。 class。

As per my thoughts, we should make a class as Singleton when we share the same object state across the application. In that case we want the user to to restrict from creating a new instance every time so that they could not maintain the multiple states. Agreed. But the same behavior can be acheved by by declaring the instance variables as static. To me it looks it will also serve the same purpose whether its cacheobjectcontainer, logger or Classloader class.

请帮助我理解上面的概念,其中静态实例变量无法解决目的而且类需要声明为Singleton?

Please help me to understand above concept where static instance variable will not solve the purpose and class needs to be declared Singleton?

编辑部分

好的,让我更清晰一些。单例类的目的是在jvm中只保留一个单例类的实例。同意。但我试图想出为什么我们只想保留一个实例的原因。 可能有两个原因:

Ok let me bring some more clarity . The pupose of singleton class is to keep only one instance of singleton class across jvm. Agreed. But i am trying to think of reasons why we want to keep only one instance. There can be two reasons:

1)创建对象可能很昂贵。所以我们只想保留一个实例。在这种情况下同意将实例变量声明为静态并不能解决任何问题。

1) Object might be expensive to create. So we just want to keep only one instance. Agreed in this scenario declaring instance variables as static does not solve any purpose.

2)我们希望跨应用程序共享相同的对象状态。我认为这是将类声明为单例的主要目的。但它可以简单地通过将实例变量声明为静态来实现。

2) We want to share the same state of object across application. I was thinking this is the main purpose of declaring the class as singleton. But it can be achieved simply by declaring the instance variables as static.

但是看起来像1是将任何类声明为静态而不是原因2的主要原因,因为它可以是用静态变量也可以实现。

But looks like 1 is the main reason of delaring any class as static not reason 2 because it can be achieved with static variable also.

这是正确的吗?

推荐答案

声明实例变量使该引用成为静态对象。这意味着 类只有一个实例。但它不会阻止任何其他人做 new SomeObject(),无论它是否是静态引用。拥有单例类的想法是控制实例。例如,如果您使构造函数 private ,则无法执行 new 来创建新实例。因此,您正在控制实例的创建。

Declaring the instance variable makes that reference a static object. Meaning there is only one instance of it for that class. But it doesn't stop anybody else from doing new SomeObject() regardless of if it is static reference. The idea of having a singleton class is to control the instances. For example, if you make the constructor private, you cannot do a new to create a new instance. Hence, you are controlling the creation of the instances.

这篇关于什么时候我们应该在Java中使用Singleton类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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