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:-

  1. Early Instantiation: creation of instance at load time.
  2. Lazy Instantiation: creation of instance when required.

 

How to design a singleton class :-

  1. Declaring constructor of singleton class as private so that no other class can instantiate or make objects from it.
  2. Creating private static member which gets memory only once.
  3. 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.

class Early{  
       private static Early obj=new Early();
       private Early(){}     
       public static Early getEarly(){  
            return obj;  
       }    
       public void doSomething(){  
           //write something  
       }  
}  

 

Lazy Instantiation of Singleton Pattern:-

The Instance of the class is created in synchronized block so that instance is only created when required.

class Lazy{  
       private static Lazy obj;  
       private Lazy(){}     
       public static Lazy getLazy()
       {  
             if (obj == null)
          {  
                synchronized(Singleton.class){  
                      if (obj == null){  
                             obj = new Singleton();
                     }  
                }              
           }  
           return obj;  
     }  
   public void doSomething(){  
          //Write something 
    }   
}  

 

Also Readhttps://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.

 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..