[ 单例模式 ] 的常用写法

2017-01-11  本文已影响17人  _秋天

1.饿汉式

优点 : 写法比较简单 , 在类加载的时候 , 完成实例化 , 避免了线程同步问题。
缺点 : 在类加载的时候完成实例化 , 如果这个类没有被使用过 , 就造成了内存的浪费。

public class Singleton {
    private  final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }
}

2.懒汉式

优点 : double check , 线程安全 , 延迟加载

public class Singleton {
    private static volatile Singleton singleton;

    public static Singleton getInstance(){
        if (singleton == null){
            synchronized(Singleton.class){
                if (singleton == null){
                    singleton = new Singleton();
                }
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读