I usually create singleton classes using singleton holder pattern like this:
public class Foo {
private static final class SingletonHolder {
private static final Foo INSTANCE = new Foo();
}
private Foo(){}
public static final Foo getInstance(){
return SingletonHolder.INSTANCE;
}
}
Everything ok. But, what about if I need inject one dependency to initialize the singleton object?
In that case, I add one method initialize that receives the dependency and must be called just one time:
public class Foo {
private static final class SingletonHolder {
private static final Foo INSTANCE = new Foo();
}
private Foo(){}
public static final void initialize(Dependency d) {
SingletonHolder.INSTANCE.setDependency(d);
}
public static final Foo getInstance(){
return SingletonHolder.INSTANCE;
}
}
Am I in the right way? Is there another solution? I know that it depends on the program, my logic and so on... but how generally should be solved this problem?