My question is that when we call getInstance() in singleton for the first time,then all its static properties are loaded in memory, i.e. before that it is not loaded in memory, so actually checking being null in the getInstance method is practically pointless and practically no different from the eager method, so why do we use this?
//lazy
class Singleton{
private static Singleton singleton;
private Singleton(){}
public Singleton getInstance(){
if (singleton==null) // this two lines
singleton=new Singleton(); // are useless I think
return singleton;
}
}
//eager
class Singleton{
private static Singleton singleton=new Singleton(); //before calling the getInstance()
//the singleton is not initialized so inline initializing is not a problem
private Singleton(){}
public Singleton getInstance(){
return singleton;
}
}
Aucun commentaire:
Enregistrer un commentaire