单例设计模式的两种写法

2017-01-03  本文已影响0人  Goorwl

懒汉式

public class Singleton {
    private volatile static Singleton instance; //声明成 volatile
    private Singleton (){}

    public static Singleton getSingleton() {
        if (instance == null) {                         
            synchronized (Singleton.class) {
                if (instance == null) {       
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

饿汉式(静态内部类)

public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE; 
    }  
}

具体解释参考:http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

上一篇 下一篇

猜你喜欢

热点阅读