Java面试总结-设计模式

单例

/**
 * 单例模式  要考虑的三点因素
 * <p>
 * 1. 线程安全
 * 2. 延迟加载
 * 3. 序列化与反序列化安全
 */
public class Singleton {
    //使用volatile保证线程的可见性,
    private static volatile Singleton singleton = null;
    //这里写个私有的构造函数是防止在外部可以直接new这个对象
    private Singleton() {

    }
    public static Singleton getSingleton() {
        if (singleton == null) {//添加判断减少排队,提高效率
            //加锁保证线程安全
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24067089/article/details/88657368