0

最近我学习了单例模式。并且不得不意识到一个。例如:

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
    }
}

但早些时候我会意识到这个是这样的:

public class Singleton {
    private static InnerObject innerObject;

    static {
        innerObject = new InnerObject();
    }

    public static InnerObjectResult getResult() {
        return innerObject.getResult();
    }
}

因此结果是一样的:innerObject 初始化了一次,但代码更简洁,我不必担心多线程。我知道这种模式并不依赖于特定的语言,可能你不能在其他地方做这样的事情,但我对这种特殊情况很感兴趣。非常感谢!

4

0 回答 0