gpt4 book ai didi

java - 单例对象——在静态 block 中或在 getInstance() 中;应该使用哪个

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:44 24 4
gpt4 key购买 nike

下面是实现单例的两种方式。各有什么优缺点?

静态初始化:

class Singleton {
private Singleton instance;
static {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}

惰性初始化是:

class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
return instance;
}
}

最佳答案

  1. 同步访问器

    public class Singleton {
    private static Singleton instance;

    public static synchronized Singleton getInstance() {
    if (instance == null) {
    instance = new Singleton();
    }
    return instance;
    }
    }
    • 延迟加载
    • 表现不佳
  2. 双重检查锁定和 volatile

    public class Singleton {
    private static volatile Singleton instance;
    public static Singleton getInstance() {
    Singleton localInstance = instance;
    if (localInstance == null) {
    synchronized (Singleton.class) {
    localInstance = instance;
    if (localInstance == null) {
    instance = localInstance = new Singleton();
    }
    }
    }
    return localInstance;
    }
    }
    • 延迟加载
    • 高性能
    • JDK 应该是 1,5++
  3. On Demand Holder 成语

    public class Singleton {

    public static class SingletonHolder {
    public static final Singleton HOLDER_INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
    return SingletonHolder.HOLDER_INSTANCE;
    }
    }
    • 延迟加载
    • 高性能
    • 不能用于非静态类字段

关于java - 单例对象——在静态 block 中或在 getInstance() 中;应该使用哪个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com