Everything You Need To Know About Singleton Class
Posted By : Lakshmi Singh | 29-Oct-2021
When it comes to defining a Singleton class, it falls under one of the five creational singleton design patterns in Java. It is termed under creational design patterns in java.
It limits the number of object creation of a class to only one. These are used in the multi-threaded and database applications for caching, logging, thread pooling, configuration settings and much more.
There are two defined terms of singleton classes:-
- Early Instantiation: creation of instance at load time.
- Lazy Instantiation: creation of instance when required.
How to design a singleton class :-
- Declaring constructor of singleton class as private so that no other class can instantiate or make objects from it.
- Creating private static member which gets memory only once.
- Declare a static factory method with the return type as an object of this singleton class.
Early Instantiation of Singleton Pattern:-
Instance of the class is created during the declaration of static member .i.e at the time of classloading.
Lazy Instantiation of Singleton Pattern:-
The Instance of the class is created in synchronized block so that instance is only created when required.
Also Read : https://www.geeksforgeeks.org/singleton-class-java/
Advantage of Singleton classes
- Saves memory because object is not created at each request. Only a single instance is reused time and again.
- It has static initialization.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Lakshmi Singh
She is a backend Developer. She has expertise in Java, JavaScript, JQuery, HTML, CSS, PHP. She is a quick learner to new technologies and adaptive to the environment.