Blog Image

Singleton Design Pattern  

Singleton Design Pattern
Singleton design pattern is the most popular and older design pattern within the design pattern catalog.
Singleton design pattern is one of the Gangs of four Design Pattern.
If you create a class as singleton class then an application allow only one instance of that class.
Generally we create a class as singleton when we want global point of access of that instance.

How to create a class as singleton
1) Declare the constructor of the class as private.
2) Declare a static method because After declare the constructor as private no one from outside the class can call the constructor to create the object. The method of the same class can call the constructor to create the object, so in this static method I can write the code to check and return only one object of the class.
3)Declare a static member of the same class type in that class, In the static method we write the logic for returning only one instance of that class, for tracking the object we assign the object into that static member variable.

Example

package com.sjg.pattern;
public class SingleTon{
    // Declare a static member of the same class type
    private static SingleTon instance;
   
    // Declare the class constructor as private
    private SingleTon(){
       // no-op
    }
   
    public staticSingleTon getInstance(){
       if(instance == null){
           instance = new SingleTon();
       }
       return instance;
    }
}

We can write the above singleton code in various different ways
1) Eager instantiation
It is not recommended, even though we don't want the object then also the object is created. At the time of class is loading into the jvm the object is created. Because static variable is called only once at the time of class loading. If we don't use this object then also we create so the CPU memory is wasted .
Example
package com.sjg.pattern;
    class EagerInstantiationSingleton {
      private static final EagerInstantiationSingleton instance = new EagerInstantiationSingleton();
     
      //private constructor to avoid someone to create the object of the class
      private EagerInstantiationSingleton() {
        //no-op
      }
     
      public static EagerInstantiationSingleton getInstance() {
        return instance;
      }
    }

2) Static Block instantiation
It is also same as Eager instantiation, the static block is executed at the time of class loading and the object is created at that time.
Example
package com.sjg.pattern;
    class StaticInstatiationSingleton {
        private static StaticInstatiationSingleton instance;
       
        //private constructor to avoid someone to create the object of the class
        private StaticInstantiationSingleton() {
            //no-op
        }
       
        static {
            instance = new StaticInstantiationSingleton();
        }
       
        public static StaticInstantiationSingleton getInstance() {
            return instance;
        }
    }

3) Lazy instantiation
It will not work in multi threaded environment because When multiple threads are trying to access the getInstance() method ,if thread switching is happened there may be a chance of creating multiple objects.
Example
 package com.sjg.pattern;
    class LazyInstantiationSingleton{
        private static LazyInstantiationSingleton instance;
     
        //private constructor to avoid someone to create the object of the class.
        private LazyInstantiationSingleton(){
             //no-op
        }
        public static LazyInstantiationSingleton getInstance(){
         if(instance == null) {
                instance = new LazyInstantiationSingleton();
            }
          return instance;
        }
    }

4) Thread Safe Singleton
It will work in multi threaded environment also but the getInstance() method is synchronized performance will be degraded, Means if one thread is accessing the synchronized method all the other threads have to wait until the 1st thread completed it's work.
Example
package com.sjg.pattern;
    class ThreadSafeSingleton{
      private static ThreadSafeSingleton instance;
     
        //private constructor to avoid someone to create the object of the class
        private   ThreadSafeSingleton() {
        //no-op
      }
    public static synchronized ThreadSafeSingleton getInstance() {
        if(instance == null) {
          instance = new ThreadSafeSingleton();
        }
      }
    }

5) Double Checking Process
To overcome the above problems we are using double checked process. In this case we are using synchronization in block level and we are creating the object inside synchronization block. Then we can improve the performance by using double Checking process.
Example
 package com.sjg.pattern;
  class DoubleCheckingSingleton {
    private static DoubleCheckingSingleton instance;
   
    //private constructor to avoid someone to create the object of the class
    private DoubleCheckingSingleton() {
        //no -arg
    }
   
    public static DoubleCheckingSingleton getInstanceUsingDoubleChecking() {
      if(instance == null) {
        synchronized(DoubleCheckingSingleton.class) {
            if(instance == null) {
              instance = new DoubleCheckingSingleton();
                }  
            }
        }
      return instance;
    }
  }

Test Class for DoubleCheckingSingleton class
  import com.sjg.pattern.DoubleCheckingSingleton;
    public class SingleTonTest {
        public static void main(String[] args) {
            DoubleCheckingSingleton singleTon1 = null;
            DoubleCheckingSingleton singleTon2 = null;

            singleTon1 = DoubleCheckingSingleton.getInstanceUsingDoubleChecking();
            singleTon2 = DoubleCheckingSingleton.getInstanceUsingDoubleChecking();

            System.out.println("singleTon1 : " + singleTon1.hashCode());
            System.out.println("singleTon2 : " + singleTon2.hashCode());
        }
    }

Output:
singleTon1 : 366712642
    singleTon2 : 366712642
    (Both the object hashCode is same)

Attachments

About author

User Image
ManasPanda

Myself Manas Ranjan Panda and I am from Kalahandi, a District of state Odisha. I am a java Developer in one of the Software Company. I am Technically sound in Java Programming and I am very much comfortable with Web Application Development. I have good knowledge on Spring framework, Web Services, Hibernate, Restful Services, oracle, MySQL, HTML, CSS, JavaScript, Ajax, Json etc.

6

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      flysunil
      06-9-2017 10:48:10 PM

    Thanks Manas! for your precious effort, it's really easy to understand bz of the example-led approach for each concept its really appreciable.

  • author image
    by:
      Thakare
      24-8-2017 10:59:39 AM

    How can i restrict that no one can serialize my Singleton class Object? In my Singleton class can be super class for other classes?

  • author image
    by:
      Sumit1234
      12-8-2017 05:34:25 AM

    So good to see this blog Manas S. It helps a lot. It easy to understand as you explained in a way like that.

  • author image
    by:
      PRAVESH4021
      27-4-2017 06:34:30 AM

    Thanks bro please upload details about factory desing pattern and when we use singlton or when we use factory degin pattern clearly post ...please

  • author image
    by:
      ManasPanda
      22-4-2017 08:03:37 AM

    You want to upload a blog like above or any thread (java related any query), if you want to upload a blog then you should became a moderator....

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.