Sunday, February 7, 2016

Correct Singleton Class implemnetaion

This is a very basic design pattern question asked by the interviewer. There are multiple ways to implement Singleton class using Java.

Here is a correct way of implementation:

===
class Singleton {
 private volatile static Singleton _instance;//do not initialize here

private Singleton() { //mark it private to prevent Singleton object to be instantiated from outside

}

public static Singleton getInstance() {
 if (_instance == null) { 
  synchronized (Singleton.class) { 
   if (_instance == null) { 
    _instance = new Singleton();
    }
   }
  }
 return _instance;
}
===

No comments:

Post a Comment