What is Singleton Design Pattern?
Singleton is the simplest form of the design patterns, singleton means something singular which means having only one. in a Java program, a singleton object means creating only one object for the entire application. (per JVM). and this object is globally accessible within the application.
Singleton design pattern is used for the performance-critical objects. as an example, Think of creating a database connection object which establishes the connection from the application to the database. For each user or for each request a connection object has to be created this causes performance bottlenecks.
And if there are multiple objects from the same class related to the application configuration and preferences even at that time the application cause issues.
To avoid these conflicts in application programmers use the Singleton Design pattern. Singleton's design pattern has two main objectives.
- Enforces one and only one object of a Singleton class.
- Globally Access through the application.
Implementing a Singleton class.
In the above example, we create a printer configuration instance, first, we create a initialize class from the “PrinterInstance ” and making it private and volatile which makes the object cannot be modified from the outside of the class. and state remained as same even in the multiple threads.
And the constructor of the class is set to private to avoid being creating objects. to make sure the object initialization is protected even via the reflection API extra checking should be done inside the constructor whether the object is initialized or not.
And expose only one method to create an object and do the double-checking inside the “getInstance()” method to ensure that more than one thread can access concurrently and does not instantiate the object more than once.
Complete Source code available here.