Singleton Design Pattern
Singleton Design Pattern
Singleton Design Pattern
Write a static method that has return type object of this singleton class. Here,
the concept of Lazy initialization in used to write this static method.
Normal class vs Singleton class: Difference in normal and singleton class in terms
of instantiation is that, For normal class we use constructor, whereas for
singleton class we use getInstance() method (Example code:I). In general, to avoid
confusion we may also use the class name as method name while defining this method
(Example code:II).
Implementing Singleton class with getInstance() method
Singleton class
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.
In the main class, we instantiate the singleton class with 3 objects x, y, z by
calling static method getInstance(). But actually after creation of object x,
variables y and z are pointed to object x as shown in the diagram. Hence, if we
change the variables of object x, that is reflected when we access the variables of
objects y and z. Also if we change the variables of object z, that is reflected
when we access the variables of objects x and y.
Implementing Singleton class with method name as that of class name
Explanation: In the Singleton class, when we first time call Singleton() method, it
creates an object of class Singleton 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 Singleton() method, since single_instance is not null,
it is returned to the variable, instead of instantiating the Singleton class again.
This article is contributed by Pavan Gopal Rayapati. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.