What is a Singleton Design Pattern?
Introduction
Singleton is a type of desing pattern in which the constructor is initialized
only one instance of a class in the entire codebase which is used for rest of
operation.
- It is used in creating applications like logger.
4 Ways to achieve this:
- Eager
- Lazy
- Synchronized Method
- Double locking (Industry practices)
1. Eager Initialization:
During runtine the instance gets created.
public class DBConnection{
private static DBConnection conObject = new DBConnection();
private DBConnection(){
}
public static DBConnection getInstance(){
return conObject;
}
}
public class Main{
private static void main(String args[]){
DBConnection connObject = DBConnection.getInstance();
}
}
2. Lazy Initialization:
In this the object gets intialized when required for user.
Problem:
If two
threads are called at once then 2 instances are created with 2 object
instances.
public class DBConnection {
private static DBConnection conObject;
private DBConnection(){}
public static DBConnection getInstance(){
if(conObject == null){
conObject = new DBConnection();
}
return conObject;
}
}
3. Synchronized Method:
In this the object gets intialized when required for user even various threads
call the object at once. Problem:
Its is expensive as for each threads it
locks and perform operations.
public class DBConnection {
private static DBConnection conObject;
private DBConnection(){}
synchronized public static DBConnection getInstance(){
if(conObject == null){
conObject = new DBConnection();
}
return conObject;
}
}
4. Double Locking:
It the most promosing mechanism of this singleton design pattern making the conditions met and called once when called without extra memory and resource usage.
public class DBConnection {
private static DBConnection conObject;
private DBConnection(){}
public static DBConnection getInstance(){
if(conObject == null){
synchronized(DBConnection.class){
if(conObject == null){
conObject = new DBConnection();
}
}
return conObject;
}
}
0 Comments
If you have any doubts or any topics that you want to know more about them please let me know