What is a Singleton Design Pattern?
Introduction
Single is a type of desing pattern in which the constructor is initialized
only one instance og class in the entire codebase which is used for rest of
operation.
It is used for 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:
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