Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton v/s class with static members & methods in Java [duplicate]

Possible Duplicate:
Difference between static class and singleton pattern?

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 find out, there might be two possible answers to it -

  1. When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.

  2. If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.

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 / Inheritance?

like image 221
Ranjan Maheshwari Avatar asked Oct 23 '22 07:10

Ranjan Maheshwari


2 Answers

Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.

like image 188
JB Nizet Avatar answered Oct 27 '22 11:10

JB Nizet


Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.

like image 37
Chris Gerken Avatar answered Oct 27 '22 09:10

Chris Gerken