确保一个类在整个应用中只有一个实例

package org.example;

public class Singleton {
    // 饿汉单例
    //    private static final Singleton instance = new Singleton();
    //
    //    private Singleton() {}
    //
    //    public static Singleton getInstance() {
    //        return instance;
    //    }

    // 懒汉单例,线程不安全
    //    private static Singleton instance;
    //    private Singleton() {}
    //    public static Singleton getInstance() {
    //        if (instance == null) {
    //            return new Singleton();
    //        }
    //        return instance;
    //    }

    // 懒汉式单例(线程安全, 使用同步锁)
    //    private static Singleton instance;
    //    private Singleton() {}
    //    public static synchronized Singleton getInstance() {
    //        if (instance == null) {
    //            return new Singleton();
    //        }
    //        return instance;
    //    }

    // 双重检查锁的单例模式
    // 使用volatile是为了防止指令重排序
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        // 第一次检查,如果创建了实例,直接返回,节省性能
        if (instance == null) {
            synchronized (Singleton.class) {
                // 第二次检查,不能直接创建实例,主要是为了防止有多个线程通过了第一次检查,直接创建实例就会创建多个实例了
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}