I was going through the articles on the Singleton pattern in apex and came up with an example that describes Early Initialization vs Lazy Loading in the Singleton pattern.
Early Initialization:
public with sharing class EagerInitializedSingleton {
//private static instance of the class
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid creating an instance anywhere outside of this class
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
Lazy Loading:
public with sharing class LazyInitializedSingleton {
//private static instance of the class
private static LazyInitializedSingleton instance = null;
//private constructor to avoid creating an instance anywhere outside of this class
private LazyInitializedSingleton(){}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
}
My question is, does Early Initialization make sense in Apex as the class is loaded only when it is used or referenced? If so can experts give some example in apex where Early Initializations happens?