ᴜsᴇ*_*sᴇʀ 5 java singleton static design-patterns final
将Singleton的实例声明为static或更好static final?
请参阅以下示例:
static 版
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
static final 版
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*der -2
人们使用它只是static为了解释延迟初始化。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,即使您的应用程序根本不使用实例,您也不需要始终保留该实例。仅在应用程序第一次需要时创建它。