What is the proper way to initialize java enum based singleton, if I have to initialize it before I can use the object.
I have started writing the code , but I am not sure if I am doing it right. Could you help me to implement this singleton correct for me?
public enum BitCheck {
INSTANCE;
private static HashMap<String, String> props = null;
public synchronized void initialize(HashMap<String, String> properties) {
if(props == null) {
props = properties;
}
}
public boolean isAenabled(){
return "Y".equalsIgnoreCase(props.get("A_ENABLED"));
}
public boolean isBenabled(){
return "Y".equalsIgnoreCase(props.get("B_ENABLED"));
}
}
It’s perfectly possible to create constructor for
enum:Note that:
propsfield can be final (we likefinal)propsdoesn’t have to bestaticPay attention to the last point. Since
enum-singletons are created eagerly when theenum BitCheckclass is loaded, you have no way to pass any arguments to the constructor. Of course you can throughINSTANCEdeclaration:but this doesn’t make any difference, right? What do you want to achieve? Maybe you actually need lazy-initialized singleton?