Ticker

6/recent/ticker-posts

Header Ads Widget

Responsive Advertisement

What is a Singleton Design Pattern?

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:

    1. Eager
    2. Lazy 
    3. Synchronized Method
    4. Double locking (Industry practices)
    Making object private and using static we create an singleton pattern.

    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;
        }
      }
      

    Post a Comment

    0 Comments