Enforce The Singleton property with a private constructor or an enum type
A Singleton is simply a class that is instantiated exactly once, can have only one object (an instance of the class) at a time.
To design a singleton class:
Make constructor as private.
Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization is
used to write this static method.
Example:
Could also be done as follows:
Here is what the driver class looks like:
Output:
Explanation:
In the Singleton class, when we first time call getInstance() method, it creates an object of the class with name single_instance and return it to the variable.
Since single_instance is static, it is changed from null to some object.
Next time, if we try to call getInstance() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This part is done by if condition.
Implementing Singleton class with method name as that of class name