[英]Singleton pattern: static or static final?
最好將Singleton的實例聲明為static
或static final
?
請參閱以下示例:
static
版本
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
static final
版本
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
在您的特定情況下,根本沒有區別。 而你的第二個已經是有效的決賽 。
但
撇開下面的實現不是線程安全的事實,只顯示與final的區別。
如果您的實例延遲初始化,您可能會感覺不同。 看起來懶惰的初始化。
public class Singleton {
private static Singleton INSTANCE; /error
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE ==null) {
INSTANCE = new Singleton(); //error
}
return INSTANCE;
}
}
如果你不想懶惰(並進行延遲初始化 ),那么你可能想讓它成為final
,因為你可以(故意)做這樣的事情:
class Sample {
static Object o = new Object(); // o is not final. Hence can change.
static{
o = new Object();
o = new Object();
}
}
我會建議Singleton
使用Enum
而不是這個。
人們只使用static
來計算延遲初始化 。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
這樣,即使您的應用程序根本不使用它,您也不需要始終持有實例。 僅在應用程序第一次需要時才創建它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.