单例模式

Posted by KANG's BLOG on Tuesday, March 15, 2022

饿汉模式

public class EagerSingle {
    //在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快
    private static EagerSingle single = new EagerSingle();//静态私有成员,已初始化

    private EagerSingle() {
        //私有构造函数
    }

    public static EagerSingle getInstance() {//静态,不用同步(类加载时已初始化,不会有多线程的问题)
        return single;
    }
}

双重检查模式

public class Singleton {
    private static volatile Singleton sInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (sInstance == null) {//第一次判空减少不必要的同步
            synchronized (Singleton.class) {
                if (sInstance == null) {//第二次判空,实例为空再创建对象
                    sInstance = new Singleton();
                }
            }
        }
        return sInstance;
    }
}