單例模式的實(shí)現(xiàn)方式有懶漢,餓漢含友,雙重校驗(yàn)鎖,枚舉校辩,內(nèi)部類等等窘问,寫法就不全部列舉了。Android源碼中有一個(gè)單例輔助類/frameworks/base/core/java/android/util/Singleton.java宜咒,可以實(shí)現(xiàn)懶漢式單例惠赫,寫法挺奇特的,雖然是個(gè)hide類故黑,不過拷貝出來就可以用了汉形。
package android.util;
/**
* Singleton helper class for lazily initialization.
*
* Modeled after frameworks/base/include/utils/Singleton.h
*
* @hide
*/
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
正常懶漢單例
public class SingletonDemo {
private static SingletonDemo mInstance;
public static final SingletonDemo get() {
synchronized (SingletonDemo.class) {
if (mInstance == null) {
mInstance = new SingletonDemo();
}
return mInstance;
}
}
}
懶漢+雙重校驗(yàn)單例
public class SingletonDemo {
private static SingletonDemo mInstance;
public static final SingletonDemo get() {
if (mInstance == null) {
synchronized (SingletonDemo.class) {
if (mInstance == null) {
mInstance = new SingletonDemo();
}
}
}
return mInstance;
}
}
變種懶漢單例
public class SingletonDemo {
public static final SingletonDemo get() {
return INSTANCE.get();
}
private static final Singleton<SingletonDemo> INSTANCE = new Singleton<SingletonDemo>() {
protected SingletonDemo create() {
return new SingletonDemo();
}
};
}
懶漢式單例一般都會(huì)再加個(gè)雙重校驗(yàn)的判斷,避免每次調(diào)用get()都加鎖倍阐,影響性能概疆,Android源碼中Singleton.java工具類并沒有做雙重校驗(yàn)(看了下googlesource中的Singleton.java,也是6年前提交的代碼了)峰搪,所以我們?cè)趯ingleton.java拷貝出來使用的時(shí)候可以加個(gè)雙重校驗(yàn)優(yōu)化下岔冀。Singleton.java封裝了create,get模版概耻,及get中的校驗(yàn)邏輯使套,從而SingletonDemo中的實(shí)現(xiàn)代碼就可以更加的簡(jiǎn)單:1.create()一個(gè)單例對(duì)象,2.在需要的時(shí)候get()鞠柄。