while pondering over singleton design pattern, I stuck between eager initialization singleton and static block initialization singleton pattern. Let's say eager initialization singleton class code is -
public class EagerInitSingleton {
private static final EagerInitSingleton instance = new EagerInitSingleton();
//private constructor
private EagerInitSingleton(){}
public static EagerInitSingleton getInstance(){
return instance;
}
}
and static block singleton class code as followed-
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
//static block initialization for exception handling
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
}
LETS NOT TALK ABOUT LAZY INITIALIZATION AND THREAD SAFETY HERE. I want to figure out how two static blocks in Static block singleton making a difference here.
Aucun commentaire:
Enregistrer un commentaire