When we should go for a Singleton class in Java?
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.
the main difference is that a singleton is a normal instance that you can for example use as a parameter. Singletons can also implement interfaces.
Matteo