java利用class的load機制實現單例模式

先上代碼

public class Singleton {

    private static Singleton instance = null;

    public static Singleton getInstance() {
        if(instance == null) {
            instance = SingletonLazy.lazy;
        }
        return instance;
    }

    private static class SingletonLazy {
        public static Singleton lazy = new Singleton();
    }

}

 

classloader首先會加載Singleton.class文件,運行到if(instance==null)這句的時候,如果爲空,回去加載SingletoneLazy.class。如此便實現了lazy初始化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章