-Enum approach
Java SE 1.5後多了enum的型態,enum沒有可以access的constructor,不能被extend,根據"Effective Java"指出 single-element enum是最佳實作singleton的方式
public enum Singleton{
INSTANCE;
}
-static initializer
public final class Singleton {
private static final Singleton instance = new Singleton();
//一開始即做靜態的初始
private Singleton() {
//初始化的欄位
}
public static Singleton getInstance() {
return instance;
}
}
-Synchonized approach
public final class Singleton {
private static final Singleton instance = null; //宣告為null
private Singleton() {
//初始化的欄位
}
public static synchronized Singleton getInstance() {
return instance;//確保getinstance()有synchronized避免race condition
}
}
x Boken Singleton-Double checked locking
此問題詳細介紹如下:
http://en.wikipedia.org/wiki/Double-checked_locking
public class Singleton {
private static final Singleton instance = null; //宣告為null
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
-Lazy initialization
1.initialize-on-demand holder class idiom
public final class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
2.Double-check idiom with volatile
Java SE 5後新的memory model讓volatile此關鍵字確保所有thread所取得的欄位值是最新被寫入的
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
sychonized(this)
{
if (helper == null) {
helper = new Helper();
}
}
}
}
沒有留言:
張貼留言