Ach*_*how 10 java singleton static-variables
我有2个选择:
单身模式
class Singleton{
private static Singleton singleton = null;
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
Run Code Online (Sandbox Code Playgroud)使用一个static final字段
private static final Singleton singleton = new Singleton();
public static Singleton getSingleton() {
return singleton;
}
Run Code Online (Sandbox Code Playgroud)有什么不同?(单线程或多线程)
更新:我知道Bill Pugh或enum方法.我不是在寻找正确的方法,但我只使用过1.在1或2中是否有任何差异?
ass*_*ias 10
主要区别在于,使用第一个选项时,单例将仅在getInstance被调用时初始化,而对于第二个选项,它将在加载包含类时立即初始化.
延迟和线程安全的第三个(首选)选项是使用枚举:
public enum Singleton {
INSTANCE;
}
Run Code Online (Sandbox Code Playgroud)