public class SingletonClass {
private static volatile SingletonClass sSoleInstance;
//private constructor.
private SingletonClass() {
//Prevent form the reflection api.
if (sSoleInstance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance() {
//Double check locking pattern
if (sSoleInstance == null) { //Check for the first time
synchronized (SingletonClass.class) { //Check for the second time.
// if there is no instance available... create new one
if (sSoleInstance == null)
sSoleInstance = new SingletonClass();
}
}
return sSoleInstance;
}
}
單例模式使用中常見錯誤:
1.getInstance()不要加鎖,
原因:
【1】鎖開銷會影響性能
【2】如果sSoleInstance已經初始化了,鎖機制就不需要了。
2.volatile:可以保證寫入操作在讀取操作之前發生。
public class SingletonClass implements Serializable {
private static volatile SingletonClass sSoleInstance;
//private constructor.
private SingletonClass() {
//Prevent form the reflection api.保證該私有構造函數只會執行一次,即第一次:sSoleInstance為null的時候。
if (sSoleInstance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance() {
if (sSoleInstance == null) {
//if there is no instance available... create new one
synchronized (SingletonClass.class) {
if (sSoleInstance == null)
sSoleInstance = new SingletonClass();
}
}
return sSoleInstance;
}
//Make singleton from serialize and deserialize operation.
protected SingletonClass readResolve() {
return getInstance();
}
}
上面寫法可以保證:該類事線程,反射,序列化都是安全的。
再談談為什么使用單例:
1.控制對象的創建,限制對象的數量只有一個。
2.單例允許只有一個入口來創建對象。
3.常用在控制資源,比如:數據庫連接等等。
4.單例的寫法比較多,根據不同的情況進行不同的寫法,基本圍繞上面給出的寫法。