Search This Blog

Tuesday, June 21, 2011

Create Singleton in Java

A singleton is simply a class that is instantiated exactly once.  There are two approaches to create a singleton class.
  1. Early initialization,
  2. Lazy initialization.
 There are several ways to create singleton in each approach.

For early initialization:
  1. Singleton with public final field
public class Singleton {
      public static final Singleton INSTANCE = new Singleton();

      private Singleton() {
         //do something
      }

      public void someMethod() {
         // do something
      }
    }

     2. Singleton with static factory
public class Singleton {
     private static final Singleton INSTANCE = new Singleton();
     
     private Singleton() {
         //do something
     }

     public static Singleton getInstance(){
       return INSTANCE
     }

     public void someMethod() {
         // do something
     }   
   }
  
      3. Singleton with enum
public enum Singleton {
      INSTANCE;
            
      private Singleton() {
         //do something
      }

      public void someMethod() {

         // do something
      }    
    }


For lazy initialization:

  However unless you absolutely need it, don't use lazy initialization.

     1. Lazy initialization holder class idiom for static fields (a class will not be initialized until it is used)

public class LazySingleton {
     private static class SingletonHolder {
       static final LazySingleton INSTANCE = new LazySingleton();
     }
     
     private LazySingleton() {
         //do something
     }

     public static LazySingleton getInstance(){
       return SingletonHolder.INSTANCE;
     }

     public void someMethod() {
         // do something
     }
    }

 2. Double-check idiom for lazy initialization

   class LazySingleton {
     private static volatile LazySingleton instance;
     private LazySingleton(){

        //do something
     }


     public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (
LazySingleton.class) {
                if (instance == null) {
                    INSTANCE = new LazySingleton();
                }
            }
        }
        return instance;

     }
   }

No comments:

Post a Comment