單例模式可以算是所有設(shè)計(jì)模式中用的最多也最好理解的一種設(shè)計(jì)模式了项栏,還記得當(dāng)初剛剛?cè)腴T那會(huì)彬伦,去面試,有一道筆試題就是手寫“餓漢式”和“懶漢式”兩種單例模式的代碼虐拓。
廢話不多說(shuō)心俗,直接上代碼:
餓漢式
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
懶漢式(雙重校驗(yàn))
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
以上這兩種是常用的寫法,那天蓉驹,我在閱讀ActivityManager源碼的時(shí)候城榛,以下代碼引起了我的注意:
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
從名字我們也知道,這應(yīng)該是一種單例模式态兴,其關(guān)鍵就在于Singleton這個(gè)類狠持,找了一下,這個(gè)類是在android.util包下的瞻润,但屬于隱藏類喘垂,我們無(wú)法直接使用,但是我們可以copy一份出來(lái)嘛:
public abstract class Singleton<T> {
private volatile T mInstance;
protected abstract T create();
public final T get() {
if (mInstance == null) {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
return mInstance;
}
}
代碼也很好理解绍撞,這就是上面說(shuō)的懶漢式(雙重校驗(yàn))正勒,然后用泛型進(jìn)行抽象封裝,方便使用傻铣,挺好的一個(gè)工具類章贞!
事實(shí)證明,耐心地閱讀源碼總會(huì)有意外收獲的非洲,共勉之阱驾!