Tag: creational design pattern

Singleton – Creational Design Pattern

Singleton Design Pattern is one of the creational design pattern which creates only one instance of the class. Only one instance of the class is created per Java Virtual Machine. Singleton pattern is used for logging, drivers object and thread pool. There are different ways to create singleton design pattern, but all of them follow three concepts

  1. private constructor to restrict access to other classes.
  2. private static variable of the same class that is only instance of the class.
  3. public static method to return the instance of the class.
class SingletonPattern {
   private static SingletonPattern defaultInstance;
   private SingletonPattern() { }
   public static SingletonPattern getInstance() {
      if(defaultInstance == null) {
         System.out.println("Singleton Pattern Default Instance Created");
         defaultInstance = new SingletonPattern();
      }
      return defaultInstance;
   }
}

The above singleton class is not thread-safe and may not be useful in multi-thread environment. Need to take necessary steps to make it thread safe. The below method of creating singleton pattern is the most widely used and doesn’t require any synchronization techniques.

class SingletonPattern {
    private SingletonPattern() { }	
    private static class SingletonHelper {
        private static final SingletonPattern INSTANCE = new SingletonPattern();
    }
    public static SingletonPattern getInstance() {
        return SingletonHelper.INSTANCE;
    }
}
Advertisements