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

Android 源碼中的裝飾模式:透視 ContextWrapper 的設計

編輯:關於 Android 程式設計

如果要說 Android 源碼中哪個地方把裝飾模式用得最淋漓盡致,那非 ContextWrapper 莫屬——它是一個幾乎完全透明的經典裝飾器。本文以裝飾模式為視角,剖析 Context 家族的源碼結構。分析基於 Android 5.0.0 源碼。

一、裝飾模式速覽

意圖

動態地為對象添加額外職責。就「擴展功能」而言,它比繼承子類的方式靈活得多。

UML

一段最小示例

class Component {
    public void operate1() {
        System.out.println("operate1");
    }
}

class ComponentDecorator extends Component {
    private Component mComponent;

    public ComponentDecorator(Component component) {
        mComponent = component;
    }

    public void operate1() {
        System.out.println("print before");   // 添加的職責
        mComponent.operate1();                // 仍調用被裝飾對象的操作
    }
}

class ComponentChild {
    public void operate1() {
        System.out.println("child operate1");
    }
}

public static void main(String[] args) {
    ComponentChild component = new ComponentChild();
    ComponentDecorator decorator = new ComponentDecorator(component);
    decorator.operate1();
}

核心思路很簡單:把被裝飾對象作為裝飾器的成員變量,調用裝飾器的方法時,裝飾器既會轉發給被裝飾對象,也能在前後插入自己的邏輯。

「透明」的裝飾器要求接口與被裝飾對象完全一致、不新增方法;實踐中更多採用「半透明」形式。相比子類化,裝飾模式的好處在於:它能裝飾各種子類,甚至能裝飾另一個裝飾器(裝飾器互相嵌套),靈活性遠高於繼承,也不會導致子類數量爆炸。

二、ContextWrapper

下面看 Android 源碼中的實際用法(裝飾器別名 Wrapper)。先看類圖:

Context

它是應用的全局環境接口,具體實現由系統提供,負責訪問應用資源、啟動 Activity 與 Service、發送廣播等。它是一個抽象類,內部全是方法聲明,應該把它當作接口來看待。

ContextWrapper

Context 的包裝器,內部持有一個 mBase 成員——ContextWrapper 裝飾的就是這個 mBase。

ContextThemeWrapper / Activity / Application / Service / ReceiverRestrictedContext

ContextThemeWrapper 是「帶主題」的裝飾器,Activity 是它的子類;Application、Service、ReceiverRestrictedContext 則直接繼承自 ContextWrapper。每個應用都有一個 Application,源碼中可見 EmailApplication、LauncherApplication、Browser 等實現。

ContextImpl

真正實現 Context 的類。它承載了所有與環境相關的操作:

  • getResources() —— 資源管理(getAssets、layout、string、drawable 等)
  • getPackageManager() —— 包管理器
  • getContentResolver() —— 獲取內容模型,例如訪問 ContentProvider
  • startActivity() —— 啟動 Activity
  • startService / bindService / unbindService / stopService
  • registerReceiver / unregisterReceiver / sendBroadcast

getResources

ContextImpl 內部有一個 mResources 成員,由 ResourceManager 生成,所有資源讀取都經過它。目前很多 Android 資源動態加載方案,正是通過替換這個對象來實現的:

AssetManager assets = AssetManager.class.newInstance();
try {
    Method method = AssetManager.class.getMethod("addAssetPath", String.class);
    method.invoke(assets, dexPath);   // dexPath 為動態 dex 包路徑
} catch (Exception e) {
    e.printStackTrace();
}
Resources r = new Resources(assets,
        getResources().getDisplayMetrics(), getResources().getConfiguration());

注意 addAssetPath 是隱藏方法,必須反射調用。

順帶梳理一下 Android 資源框架的整體過程:

  • 編譯時根據 layout、values、drawable 等生成資源 ID,集中保存在 R 文件中;系統自帶資源在 com.android.R 中。assets 不分配 ID。
  • 通過資源目錄後綴適配不同語言、屏幕尺寸(如 drawable-en-w360)。系統按既定順序匹配,drawable 採取「不超過設備參數最大值」的原則,打包時會建立索引並寫入 resources.arsc。

運行時的讀取過程:

  • 先剔除與當前環境完全不匹配的資源目錄(例如系統是中文環境,則排除 en 目錄)。
  • assets 由 AssetManager 訪問;其餘資源按 MMC 表的順序逐維度匹配、篩選,直到找到目標資源,否則拋出異常。

getPackageManager

返回包管理器,負責管理系統中所有已安裝應用的信息:查詢指定包名的應用信息、指定組件的組件信息、安裝與卸載、權限相關操作等。在 Android 中,包名唯一對應一個應用,所以理解 PackageManager 的關鍵就是「一切以包(應用)為粒度」。更多信息可參考羅升陽的相關博客。

getContentResolver

返回 ContentResolver,它是訪問 Content 模型的入口,ContentProvider 正是通過它被外部訪問。

Activity 相關操作

簡化來看,Activity 的啟動主要經過兩步:

  1. mMainThread.getInstrumentation().execStartActivity(...)。mMainThread 是 ActivityThread 類型,管理應用主線程的調度(Activity、Broadcast 等);Instrumentation 屬於 Android 測試框架,內部通過 ActivityMonitor 監控被調用的 Activity,可以用它等待指定 Activity 啟動,甚至阻止啟動。這一層設計的主要目的就是為了讓測試能精確控制 Activity 的啟動行為,並在啟動後拿到返回結果。
  2. 監控流程結束後,通過 ActivityManagerNative 真正啟動目標 Activity:
int result = ActivityManagerNative.getDefault()
        .startActivity(whoThread, who.getBasePackageName(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()),
                token, target != null ? target.mEmbeddedID : null,
                requestCode, 0, null, options);

看到 Native 就能想到它走的是進程間通訊:ActivityManagerProxy 通過 Binder 訪問 ActivityManagerService。AMS 是 Activity、Service、Broadcast 管理的核心服務,其 startActivity 會經過 mStackSupervisor 與 ActivityStack 處理,再通過 ApplicationThread 抵達主線程的 Handler(H),最終完成 Activity 的啟動。

Service 相關操作

Service 包含 startService、stopService、bindService、unbindService。它同樣由 AMS 管理,但具體由其中的 ActiveServices 負責,最終控制流程仍會回到主線程 Handler。

BroadcastReceiver 相關操作

Context 中的 sendBroadcast、registerReceiver、unregisterReceiver,都會經 ActivityManagerNative 轉到 AMS 的對應函數。AMS 內部維護著注册的 ReceiverList:注冊時保存下來,發送廣播時依據 IntentFilter 匹配出對應 Receiver;此外還有 sticky 機制——注冊時若已有匹配的粘性廣播,會立刻投递给該 Receiver。

Activity 與 Service 的完整啟動流程可參考羅升陽的博客。需要提醒的是,他的文章基於較早的 Android 版本,如今不少細節已經變化,建議把它當作入門線索,最新實現仍需自己動手讀源碼。

三、為什麼這裡適合裝飾模式

看清結構之後,問題變成:為什麼 Context 這一部分要用裝飾模式?答案在於它能非常方便地「按需添加職責」。比如 ReceiverRestrictedContext 就能限制 Receiver 調用 startService,使廣播接收者無法直接啟動服務。透過裝飾器,可以針對不同組件提供各具差異的環境包裝,同時又共享同一套基礎實現。

與繼承方式對比

假設改用繼承來實現:Application、ThemeContext、Service 都得直接繼承自 ContextImpl。一旦需要一種新的 Context 實現,新 ContextImpl 寫完後,Application 等所有子類又得跟著重新繼承一遍——既麻煩,又會讓繼承樹變得異常龐大。而裝飾模式只需把 ContextWrapper 裝飾的對象替換掉即可。

與策略模式對比

Context 的特點是需要在外部不斷疊加新的職責裝飾,這正是裝飾模式的擅長場景;而策略模式替換的是系統「內部」的實現。如果需求是多種可互換的 Context 實現,策略模式更合適。在 Android 中,應用的運行環境是確定的,不會因應用而異,因此這裡重點是「疊加裝飾」而非「替換算法」。

當然,源碼中也存在 MockContext 這樣的實現,主要用於測試,從某個角度看也帶有策略的意味。但正常運行時,這裡真正強調的仍是不同層次的裝飾——這也正是裝飾模式的價值所在。


縱然傷心,也不要愁眉不展,因為你不知是誰會愛上你的笑容 —— 泰戈爾《飛鳥集》

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