gpt4 book ai didi

java - 单例模式 : static or static final?

转载 作者:搜寻专家 更新时间:2023-11-01 00:55:38 37 4
gpt4 key购买 nike

将 Singleton 实例声明为 static 还是声明为 static final 更好?

请看下面的例子:

静态版本

public class Singleton {

private static Singleton instance = new Singleton();

private Singleton() {
}

public static Singleton getInstance() {
return instance;
}

}

静态最终版本

public class Singleton {

private static final Singleton INSTANCE = new Singleton();

private Singleton() {
}

public static Singleton getInstance() {
return INSTANCE;
}

}

最佳答案

在您的特定情况下,根本没有区别。你的第二个已经是effectively final .

但是

抛开以下实现不是线程安全的事实,仅显示与 final 的区别。

在您的实例延迟初始化的情况下,您可能会感觉到不同。看看惰性初始化。

public class Singleton {

private static Singleton INSTANCE; /error

private Singleton() {
}

public static Singleton getInstance() {
if (INSTANCE ==null) {
INSTANCE = new Singleton(); //error
}
return INSTANCE;
}

}

关于java - 单例模式 : static or static final?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371219/

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