Singleton Pattern 的幾種方式

public class Singleton {
private final static Singleton instance = new Singleton();
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton instance;
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
public class Singleton {
private volatile static Singleton instance;
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章