Friday, July 8, 2016

Java Intevriew : Classic Singleton in Java

Q: How to create a Simple singleton class in Java.
A:
public class SimpleSingleton {

   private static SimpleSingleton instance = null;
   private SimpleSingleton () {
      // we declare it private so that you cant do below:
      //NonSynchronizedSingleton t = new NonSynchronizedSingleton(); 
   }
   public static SimpleSingleton getInstance() {
      if(instance == null) {
         instance = new SimpleSingleton();
      }
      return instance;
   }
}


public class SimpleSingletonDemo {
   public static void main(String[] args) {
      SimpleSingleton tmp1 = SimpleSingleton.getInstance( ); //Line no 1
      SimpleSingleton tmp1 = SimpleSingleton.getInstance( ); //Line no 2
   }
}


It is super easy to do this.
1) Declare the constructor as private  which is a must so that the no object can be initialized.
2) From Line no 1 :  In the public static getInstance method which returns SimpleSingleton we check if instance has already been initialized which is null as of now, so it goes ahead and initialize it.
3) Next time it will come to the getInstance method at Line No 2, it will find the instance as already initialize, so it will return the same object.

Enjoy Singleton.



No comments:

Post a Comment