Recently I learned Singleton pattern. And had to realize one. For example:
public class Singleton {
private static Singleton instance;
private InnerObject innerObject; //all functionality is here
private Singleton() {
innerObject = new InnerObject();
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public InnerObjectResult getResult() {
return innerObject.getResult(); //delegate method call
}
}
But earlier I would realize this one like this:
public class Singleton {
private static InnerObject innerObject;
static {
innerObject = new InnerObject();
}
public static InnerObjectResult getResult() {
return innerObject.getResult();
}
}
Thus the result is the same: innerObject initialized once, but the code is cleaner and I don't have to worry about multithreading. I know that pattern doesn't rest on specific languages and probably you can't do something like this elsewhere, but I'm interested in this particular situation. Thank you very much!