The question is really simple, why do I need a Singleton? Why a class with static methods/variables will not do the same what a singleton is supposed to do?
I never thought about that. So, I googled for “Singleton vs Static” and here is the excerpt from the results.
A class with static utility methods can be used for exposing standalone methods (e.g. utility/helper methods). Such a class holds little or no state. On the other side a singleton, should be used whenever there is a state to store. The main advantage of Singleton over static (i.e. a class with static utility methods) is, it may use polymorphism. Ideally, a singleton should return different implementations of the class at runtime depending on the use case. To explain it further, let’s have a look of java.lang.Runtime class. The description of the class says:
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
Actually, Runtime.getRuntime() method returns a singleton object – an object which depends on the particular platform over which the JVM is running. Thus, different implementation of JVM will provide an instance of different subclasses of Runtime itself, which is designed to run on that specific platform/OS.
It sounds similar to factory! Is Singleton a factory? The idea is, Singletons can be extended into a factory. The whole process of object creation is abstracted from the API user. And hence it can be maintained or extended or changed easily. But, the fundamental difference between these two should also be kept in mind. A factory returns a new instance on each invocation of the getter method, whereas a Singleton always returns the same instance of the class. But, in most of the cases we don’t use Singleton pattern in such a way and hence Singletons does not really offer much advantage over the static.
In addition to this, if I have a Singleton, I can implement interfaces and extend classes. Lazy initialization of Singletons are possible, i.e. the Singleton object may have a shorter life time than the application containing it. MySingleton.getInstance() returns an actual object. These advantages are missing with a class with static utility methods.
To summarize, if you want to write a class with some stateless (or almost stateless) static methods, go for a class with static methods and static variables. If you need something more, as I have mentioned before, then Singleton should be your choice. But, remember, before banking on the static, analyze and think twice. It should never be the case that in future you have to rewrite the code and go back to the Singleton!
So, the final question. Is Singleton a pattern with all good? I am afraid. The answer is NO!
When is a Singleton not a Singleton?