Often, singleton pattern classes are used to broker concurrent access to a shared resource. You will see it in quite a few logger implementations. The pattern particularly useful if you have a an "expensive" resource that might not be needed during the course of the application. Since the singleton supports "lazy initialization," you only pay the cost for the resource if you actually need it. Also, supporting polymorphism for an object can be useful
Here are some difference between using classes with static methods and variables:
1. Singletons can implement interfaces and inherit from other classes.
2. Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialization includes expensive resource loading or database connections.
3. Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
Of course, don't use this as license to go "Singleton" wild. As with most design patterns, the patterns pros and cons must be carefully considered before implementation.
Ranjan Maheshwari, on 05 October 2012 - 11:31 PM, said:
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods. As far as I can understand the difference between the two is Polymorphism.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism?