Friday, March 13, 2020

One of the correct Singleton Class implementation

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