ITeye博客

java利用class的load机制实现单例模式

haiker · 2012-10-23 16:43 · 编程语言 · Java · singleton · Markdown

先上代码

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初始化。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。