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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With