学习笔记(10):第2章 架构师内功心法之设计模式 -单例模式详解(上)

立即学习:https://edu.csdn.net/course/play/28941/403575?utm_source=blogtoedu

单例模式(Singleton Pattern)——属于创见型模式。

定义:单例模式是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点。

隐藏其所有的构造方法。

单例模式的适用场景

确保任何情况下都绝对只有一个实例。(ServletContext、ServletConfig、ApplicationContext、DNPool)

单例模式的常见写法

1.饿汉式单例

2.懒汉式单例

3.注册式单例

4.ThreadLocal单例

饿汉式单例——在单例类首次加载时就创建实例

/**
 * 饿汉式单例
 * 优点:执行效率高,性能高,没有任何的锁
 * 缺点:某些时候可能造成内存浪费;*/
public class HungrySingleton {
    private static final HungrySingleton hungrySingleton = new HungrySingleton();

    private HungrySingleton(){}

    public HungrySingleton getInstance(){
        return hungrySingleton;
    }
}

// 另一种写法(类的加载顺序,先静态后动态;先上后下;先属性后方法)
public class HungryStaticSingleton {
    private static final HungryStaticSingleton hungrySingleyon;

    static {
       hungrySingleyon = new HungryStaticSingleton();
    }

    private HungryStaticSingleton(){}

    public static HungryStaticSingleton getInstance(){
        return hungrySingleyon;
    }

}

 懒汉式单例——被外部类调用时才创建实例

/**
 * 懒汉式单例
 * 优点:节省了内存;线程安全
 * 缺点:性能低
 * */
public class LazySimpleSingleton {
    private static LazySimpleSingleton instance;

    private LazySimpleSingleton(){}

    public synchronized static LazySimpleSingleton getInstance(){
        if (instance == null){
            instance = new LazySimpleSingleton();
        }
        return instance;
    }
}
/**优点:性能高了;线程安全了
缺点:程序可读性差*/
public class LazDoubleCheckSingleton {
    private volatile static LazDoubleCheckSingleton instance;

    private LazDoubleCheckSingleton(){}

    public static LazDoubleCheckSingleton getInstance(){
        // 实例为空时阻塞(检查是否要阻塞)
        if (instance == null){
            synchronized(LazDoubleCheckSingleton.class){
                // 双重检查保证线程安全性(检查是否要重新创建实例)
                if (instance == null){
                    instance = new LazDoubleCheckSingleton();
                    // 这里存在一个指令重排序的问题?
                }
            }
        }
        return instance;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43222122/article/details/107548028