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已經(jīng)初始化了啊送,鎖機制就不需要了。
2.volatile:可以保證寫入操作在讀取操作之前發(fā)生欣孤。
public class SingletonClass implements Serializable {
private static volatile SingletonClass sSoleInstance;
//private constructor.
private SingletonClass() {
//Prevent form the reflection api.保證該私有構造函數(shù)只會執(zhí)行一次,即第一次: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.控制對象的創(chuàng)建,限制對象的數(shù)量只有一個。
2.單例允許只有一個入口來創(chuàng)建對象。
3.常用在控制資源肩狂,比如:數(shù)據(jù)庫連接等等列粪。
4.單例的寫法比較多态蒂,根據(jù)不同的情況進行不同的寫法,基本圍繞上面給出的寫法泉懦。