1.對於性能要求不高,可以這樣寫
public class Singleton_1 {
private static Singleton_1 uniqueInstance;
//其他變量
private Singleton_1(){}
public static synchronized Singleton_1 getInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton_1();
}
return uniqueInstance;
}
//其他方法
}
2.靜態初始化的方式,非動態實例化;適於創建和運行時負擔不是太重,eagerly創建單例
public class Singleton_2 {
private static Singleton_2 uniqueInstance = new Singleton_2();
//其他變量
private Singleton_2(){}
public static synchronized Singleton_2 getInstance(){
return uniqueInstance;
}
//其他方法
}
3.雙重檢驗加鎖,從而減少使用synchronized(只有一次),提高性能
public class Singleton_3 {
private volatile static Singleton_3 uniqueInstance;//volatile關鍵字保證讀取過程變量的值保持不變
//其他變量
private Singleton_3(){}
public static synchronized Singleton_3 getInstance(){
if (uniqueInstance == null){
synchronized (Singleton_3.class){
if (uniqueInstance == null){
uniqueInstance = new Singleton_3();
}
}
}
return uniqueInstance;
}
//其他方法
}
更多:如何正確地寫出單例模式http://www.importnew.com/21141.html