单例模式

2020-08-11  本文已影响0人  就叫basi

懒汉式

懒加载形式;加锁影响效率
public class SingleObject {

    private static SingleObject singleObject;

    private SingleObject() {
    }

    //保证线程安全
    public static synchronized SingleObject getInstance() {
        if (singleObject == null) {
            singleObject = new SingleObject();
        }
        return singleObject;
    }

}

饿汉式

非懒加载形式;没有加锁,执行效率会提高;类加载时就初始化,浪费内存。
public class SingleObject {

    private static SingleObject singleObject = new SingleObject();

    private SingleObject() {
    }

    public static SingleObject getInstance() {
        return singleObject;
    }

}

双重检查锁

线程安全;懒加载
public class SingleObject {

    //使用volatile,保证singleObject实例是线程可见的。
    private volatile static SingleObject singleObject;

    private SingleObject() {
    }

    public static SingleObject getInstance() {
        if (singleObject == null) {
            //类锁
            synchronized (SingleObject.class) {
                if (singleObject == null) {
                    singleObject = new SingleObject();
                }
            }
        }
        return singleObject;
    }

}
上一篇下一篇

猜你喜欢

热点阅读