Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 源碼中的單例模式:定義、優點與實際案例

編輯:Android 開發實例

定義

Ensure a class has only one instance, and provide a global point of access to it.

也就是動態確保某個類別只有一個實例,並且自行建立該實例、對整個系統提供這個存取點。

如上圖所示(擷取自《Head First Design Patterns》)。

透過 private 建構子確保整個程式中只會產生一個實例,並且由類別自己負責建立(在 Singleton 內部呼叫 new Singleton())。

有什麼優點

記憶體中只有一個實例,開銷自然較小。

可以避免對資源的多重佔用。例如寫入同一個檔案時,因為只有一個實例存在,就不會出現多處同時寫入的衝突。

可以在系統中設置統一的存取點,便於最佳化與共享資源存取。

使用單例時最需要留意的,是多執行緒環境下如何避免被同時建立多個實例。《Head First Design Patterns》採用的「double-checked locking」就是為了降低 synchronization 的次數:

public class Singleton {
    /* volatile 確保多執行緒在初始化 uniqueInstance 時能正確處理這個變數 */
    private volatile static Singleton uniqueInstance;

    private Singleton() {}

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

這裡的 volatile 不能省。若沒有它,在極少數的情況下執行緒可能讀到一個「已指派但尚未完成建構」的物件參照,這是 double-checked locking 最經典的陷阱。

一、InputMethodManager

public final class InputMethodManager {
    static final boolean DEBUG = false;
    static final String TAG = "InputMethodManager";
    static final Object mInstanceSync = new Object();
    static InputMethodManager mInstance;
    final IInputMethodManager mService;
    final Looper mMainLooper;

以 static 欄位保存唯一實例:

static public InputMethodManager getInstance(Context context) {
    return getInstance(context.getMainLooper());
}

static public InputMethodManager getInstance(Looper mainLooper) {
    synchronized (mInstanceSync) {
        if (mInstance != null) {
            return mInstance;
        }
        IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE);
        IInputMethodManager service = IInputMethodManager.Stub.asInterface(b);
        mInstance = new InputMethodManager(service, mainLooper);
    }
    return mInstance;
}

防止多執行緒同時建立的做法,就是上面這段 synchronized (mInstanceSync) 搭配 null 檢查。若尚未建立,才呼叫 mInstance = new InputMethodManager(service, mainLooper);。建構子如下:

InputMethodManager(IInputMethodManager service, Looper looper) {
    mService = service;
    mMainLooper = looper;
    mH = new H(looper);
    mIInputContext = new ControlledInputConnectionWrapper(looper, mDummyInputConnection);
    if (mInstance == null) {
        mInstance = this;
    }
}

值得注意的小細節:這裡用的是「先檢查、提前 return」的寫法,語意上比傳統的双重檢查更簡潔,而且整個方法都包在 synchronized 區塊內,不必依賴 volatile。

二、BluetoothOppManager

public class BluetoothOppManager {
    private static final String TAG = "BluetoothOppManager";
    private static final boolean V = Constants.VERBOSE;

    // 建立 private static 類別實例
    private static BluetoothOppManager INSTANCE;

    /** 取得單例參照時使用的鎖 */
    private static Object INSTANCE_LOCK = new Object();

    /**
     * 取得單例實例
     */
    public static BluetoothOppManager getInstance(Context context) {
        synchronized (INSTANCE_LOCK) {
            if (INSTANCE == null) {
                INSTANCE = new BluetoothOppManager();
            }
            INSTANCE.init(context);
            return INSTANCE;
        }
    }

三、AccessibilityManager

public final class AccessibilityManager {
    private static final boolean DEBUG = false;
    private static final String LOG_TAG = "AccessibilityManager";

    static final Object sInstanceSync = new Object();
    private static AccessibilityManager sInstance;

    public static AccessibilityManager getInstance(Context context) {
        synchronized (sInstanceSync) {
            if (sInstance == null) {
                IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
                IAccessibilityManager service =
                        IAccessibilityManager.Stub.asInterface(iBinder);
                sInstance = new AccessibilityManager(context, service);
            }
        }
        return sInstance;
    }

    public AccessibilityManager(Context context, IAccessibilityManager service) {
        mHandler = new MyHandler(context.getMainLooper());
        mService = service;
        try {
            final int stateFlags = mService.addClient(mClient);
            setState(stateFlags);
        } catch (RemoteException re) {
            Log.e(LOG_TAG, "AccessibilityManagerService is dead", re);
        }
    }

其他像是不少 Hardware、策略相關的 Manager 也都用了同一套模式。

把這三個案例擺在一起看,可以歸納出 Android framework 對單例的慣例:用一個獨立的 lock 物件(mInstanceSync、INSTANCE_LOCK、sInstanceSync)搭配 synchronized 區塊,實例以 static 欄位保存,對外只暴露 getInstance()。這種寫法讀起來比嵌套的 double-check 更直白,也避開了 volatile 語意上的爭議,值得在自己的專案中沿用。

新年第一週,就從最簡單的單例模式開始記錄學習過程。

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