单例模式

SoruxGPT
发布于 2024-08-26 / 4 阅读
0

单例模式

双重检查锁(Double-Checked Locking, DCL)的单例模式

public class Singleton {
​
    // 构造函数私有化
    private Singleton(){}
    private static volatile Singleton INSTANCE = null;
​
    public static Singleton getInstance(){
        if(INSTANCE == null){
            synchronized (Singleton.class){
                if(INSTANCE == null){
                    INSTANCE = new Singleton();
                }
            }
        }
        return INSTANCE;
    }
}

懒汉模式

public class Singleton {
    
    private Singleton(){}
​
    private static class LazyHolder{
        static final Singleton INSTANCE = new Singleton();
    }
​
    public static Singleton getInstance(){
        return LazyHolder.INSTANCE;
    }
}