The first implementation - the actual Singleton pattern - is more flexible:
- the getInstance method could return an instance of a subclass, and
- you can pass the object around, so that not all clients need to know it's a singleton.
And there is an even more flexible pattern - the Just Create One pattern.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Could anybody explain why we required singleton class at all???
Marking your constructor private will prevent your clients from instantiating you class directly. If suppose they want to access your class instance methods they need an instance of your class. So how do they get an instance of your class?
If you look at the first example provided Susan Oso, you can understand why Singleton is needed?
Generally we use the singleton design pattern for factory classes, manager classes and classes for which we want only once instance in the whole application. It generally comes in very handy in Java swing programming.