Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When we should go for a Singleton class in Java?

Tags:

java

singleton

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.

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

Edited Part

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) 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) 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.

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.

Is this correct?

like image 823
M Sach Avatar asked Aug 26 '11 16:08

M Sach


1 Answers

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.

like image 107
Amir Raminfar Avatar answered Sep 19 '22 21:09

Amir Raminfar