Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 設計模式之單例模式:餓漢式、懶漢式與執行緒安全

編輯:關於 Android 程式設計

設計模式是前人開發過程中累積出來的经验。依實際情境套用合適的模式,可以讓程式結構更單純,也更容易擴充與維護。但反過來說,並不是用了設計模式的程式就一定比較好——簡單的小程式硬套模式,反而有畫蛇添足的味道。

單例模式大概是最簡單的一種:無論如何只能建立一個實例。常見寫法有兩種,懶漢式與餓漢式。

一、餓漢式

類別被載入時就立刻建立實例,不必等到第一次呼叫。這種寫法天生執行緒安全,代價是無論有沒有人用,實例都會被配置。

package com.dzt.singleton;

/**
 * 餓漢式,執行緒安全
 */
public class SingletonHungry {

    private static SingletonHungry instance = new SingletonHungry();

    private SingletonHungry() { }

    public static SingletonHungry getInstance() {
        return instance;
    }
}

二、懶漢式(未加同步)

把實例延後到第一次使用時才建立,但這個版本在多執行緒環境下不安全——多個執行緒同時通過 null 判斷,就可能建立出多個物件。

package com.dzt.singleton;

/**
 * 懶漢式,執行緒不安全
 */
public class SingletonIdler {

    private static SingletonIdler instance = null;

    private SingletonIdler() { }

    public static SingletonIdler getInstance() {
        if (instance == null) {
            instance = new SingletonIdler();
        }
        return instance;
    }
}

三、加上方法同步

最直接的修法是在 getInstance 上加 synchronized。安全了,但每次呼叫都要檢查一次鎖,在高频场景下開銷偏高。

package com.dzt.singleton;

/**
 * 懶漢式,加方法同步
 */
public class SingletonIdler {

    private static SingletonIdler instance = null;

    private SingletonIdler() { }

    public synchronized static SingletonIdler getInstance() {
        if (instance == null) {
            instance = new SingletonIdler();
        }
        return instance;
    }
}

四、同步區塊(雙重檢查)

進一步改良:只在第一次真的需要建立時才進入同步區塊,後續呼叫只做一次 null 判斷就返回,大幅減少鎖競爭。

package com.dzt.singleton;

/**
 * 懶漢式,同步區塊
 */
public class SingletonIdler {

    private static SingletonIdler instance = null;

    private SingletonIdler() { }

    public static SingletonIdler getInstance() {
        if (instance == null) {
            synchronized (SingletonIdler.class) {
                if (instance == null) {
                    instance = new SingletonIdler();
                }
            }
        }
        return instance;
    }
}

這就是所謂的雙重檢查鎖定(Double-Checked Locking)。在 Java 5 以前,由於指令重排序可能讓其他執行緒拿到「尚未完成初始化」的物件,因此必須把欄位宣告為 volatile 才能完全正確。若專案支援 Java 5 以上且追求簡潔,也可以考慮用靜態內部類別(Initialization-on-demand holder)或單元素列舉來實作,兩者都懶加載且天生執行緒安全。

Android 原生架構中的單例

單例模式在 Android 原生應用裡也隨處可見,例如 Phone 的 NotificationMgr:

private static NotificationMgr sInstance;

private NotificationMgr(PhoneApp app) {
    mApp = app;
    mContext = app;
    mNotificationManager = (NotificationManager) app
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mStatusBarManager = (StatusBarManager) app
            .getSystemService(Context.STATUS_BAR_SERVICE);
    mPowerManager = (PowerManager) app
            .getSystemService(Context.POWER_SERVICE);
    mPhone = app.phone;
    mCM = app.mCM;
    statusBarHelper = new StatusBarHelper();
}

static NotificationMgr init(PhoneApp app) {
    synchronized (NotificationMgr.class) {
        if (sInstance == null) {
            sInstance = new NotificationMgr(app);
            // 更新啟動時需要處理的通知
            sInstance.updateNotificationsAtStartup();
        } else {
            Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
        }
        return sInstance;
    }
}

可以注意到,這裡把建構子設為 private,對外只暴露 init() 作為唯一入口,並在重複呼叫時以 Log.wtf 明確示警——這是很值得借鏡的防禦性寫法:單例被誤用時,盡早發出訊號,比默默容忍更好排查。

小結

選擇哪一種寫法,取決於實例的建立成本與使用時機:建立代價高、不確定是否會用到,就用懶漢式;建立代價低、幾乎一定會用到,餓漢式反而最省心。無論哪一種,都別忘了把建構子設為 private,這才是單例模式的底線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved