欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第03条 用私有构造方法或者枚举类型强化Singleton属性

程序员文章站 2022-07-14 09:24:03
...

单例模式最佳写法1 - 双重校验锁

public class Singleton {

    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;
    }
}
复制代码

单例模式最佳写法2 - 静态内部类

public class Singleton {

    private Singleton() {
    }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
复制代码

转载于:https://juejin.im/post/5ca46344f265da307666b32b