单例设计模式——懒汉式(手写)

懒汉式:在使用该类的对象时才会产生实例化对象;
 

//懒汉式单例设计模式
public class Singleton {
    //private 修饰对象
    private static Singleton singleton;
    //构造方法私有化
    private Singleton() {}
    //判断,如果是第一次使用该类对象,才new 产生实例化对象
    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

会出现线程安全问题,在多线程并发情况下,会产生多个实例化对象。

解决方法:全局锁+内存屏障。

猜你喜欢

转载自blog.csdn.net/fayfayfaydyt/article/details/82121181