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

Android 開發中的 Builder 模式:以 AlertDialog.Builder 為例

編輯:關於 Android 程式設計

Builder 模式的核心思想只有一句話:把複雜物件的建構過程與它的表示分離開來,使得同樣的建構流程能產出不同的結果。

為什麼需要它

一個複雜物件往往有大量組成部件,而且這些部件的組裝順序本身可能就是一套複雜的工序。以 AlertDialog 為例,它有標題、訊息、圖示、正向按鈕、反向按鈕、中性按鈕、自訂版面……部件眾多,而「怎麼把它們組裝成一個對話框」又是另一門學問。

Builder 模式正是為了解決這件事:先分別生產各個部件,再交由另一個類負責組裝。呼叫端只需描述「我要什麼」,不必知道內部怎麼拼。

從源碼看 AlertDialog.Builder

public class AlertDialog extends Dialog implements DialogInterface {

    // 控制器,接收 Builder 成員變數 P 中的各項參數
    private AlertController mAlert;

    protected AlertDialog(Context context, int theme) {
        this(context, theme, true);
    }

    AlertDialog(Context context, int theme, boolean createContextWrapper) {
        super(context, resolveDialogTheme(context, theme), createContextWrapper);
        mWindow.alwaysReadCloseOnTouchAttr();
        mAlert = new AlertController(getContext(), this, getWindow());
    }

    // AlertDialog 的 setter 實際上都轉手呼叫 mAlert
    @Override public void setTitle(CharSequence title) {
        super.setTitle(title);
        mAlert.setTitle(title);
    }
    public void setMessage(CharSequence message) { mAlert.setMessage(message); }
    public void setCustomTitle(View customTitleView) { mAlert.setCustomTitle(customTitleView); }

    // ========== Builder 是 AlertDialog 的靜態內部類 ==========
    public static class Builder {

        // 1. 這個參數容器負責暫存 title、message、icon 等設定
        private final AlertController.AlertParams P;

        public Builder(Context context) {
            this(context, resolveDialogTheme(context, 0));
        }

        public Builder(Context context, int theme) {
            P = new AlertController.AlertParams(
                    new ContextThemeWrapper(context, resolveDialogTheme(context, theme)));
            mTheme = theme;
        }

        // 2. 各個 setter 只是把值寫進 P,並回傳 this 以支援串接
        public Builder setTitle(CharSequence title) {
            P.mTitle = title;
            return this;
        }

        public Builder setMessage(CharSequence message) {
            P.mMessage = message;
            return this;
        }

        public Builder setIcon(int iconId) {
            P.mIconId = iconId;
            return this;
        }

        public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
            P.mPositiveButtonText = text;
            P.mPositiveButtonListener = listener;
            return this;
        }

        public Builder setView(View view) {
            P.mView = view;
            P.mViewSpacingSpecified = false;
            return this;
        }

        // 3. 真正建立 AlertDialog 並把參數套用進去
        public AlertDialog create() {
            final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
            P.apply(dialog.mAlert);        // 核心:把 P 的內容灌進 mAlert
            dialog.setCancelable(P.mCancelable);
            if (P.mCancelable) {
                dialog.setCanceledOnTouchOutside(true);
            }
            dialog.setOnCancelListener(P.mOnCancelListener);
            if (P.mOnKeyListener != null) {
                dialog.setOnKeyListener(P.mOnKeyListener);
            }
            return dialog;
        }

        public AlertDialog show() {
            AlertDialog dialog = create();
            dialog.show();
            return dialog;
        }
    }
}

從這段源碼可以看出 Builder 模式的四個環節:

參數容器(AlertParams P)負責暫存所有設定,本身不做任何事。

串接式 setter 每個都 return this,讓呼叫端能寫成 new Builder(ctx).setTitle(..).setMessage(..).show() 這種流暢的形式。

延遲建立——呼叫 setter 時對話框還不存在,直到 create() 才真的 new 出物件。

組裝與表示分離——AlertDialog 只負責「怎麼畫」,Builder 只負責「要畫什麼」。

P.apply() 做了什麼

public void apply(AlertController dialog) {
    if (mCustomTitleView != null) {
        dialog.setCustomTitle(mCustomTitleView);
    } else {
        if (mTitle != null)   dialog.setTitle(mTitle);
        if (mIcon != null)    dialog.setIcon(mIcon);
        if (mIconId >= 0)     dialog.setIcon(mIconId);
        if (mIconAttrId > 0)  dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
    }
    if (mMessage != null) dialog.setMessage(mMessage);

    if (mPositiveButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_POSITIVE,
                mPositiveButtonText, mPositiveButtonListener, null);
    }
    if (mNegativeButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                mNegativeButtonText, mNegativeButtonListener, null);
    }
    if (mNeutralButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                mNeutralButtonText, mNeutralButtonListener, null);
    }
    // 列表、自訂 View 等其餘設定省略
    if (mView != null) {
        if (mViewSpacingSpecified) {
            dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop,
                    mViewSpacingRight, mViewSpacingBottom);
        } else {
            dialog.setView(mView);
        }
    }
}

本質上就是把 P 裡的值逐項搬到 AlertController(也就是 AlertDialog 的 mAlert)中。這也解釋了一個常見疑問:為什麼不透過 Builder、直接呼叫 AlertDialog 的 setter 也可以?因為兩條路最終都匯流到同一組 mAlert 方法,Builder 只是把「設定」與「建立」這兩個時點拆開而已。

這個模式帶來的好處

可讀性。串接式寫法讓「這個對話框長什麼樣子」變成一段近乎自然語言的描述。

可選參數不必靠多載爆炸。若沒有 Builder,AlertDialog 可能需要十幾個建構子多載來涵蓋各種參數組合。Builder 讓呼叫端只設定自己關心的部分,其餘維持預設。

建構過程可 reuse。同一個 Builder 設定好之後,可以呼叫多次 create() 產生多個內容相同的對話框。

不變性。參數在 create() 之前是可變的,建立之後 AlertDialog 的狀態就固定了,外部無法再任意竄改。

延伸思考:與「池」的關聯

Java 實務中經常使用「池(Pool)」的概念——當資源提供者無法供應足夠資源,而這些資源又需要被大量使用者反覆共享時,就需要池化。池本質上是一段被重複利用的記憶體,例如資料庫連線池。

池化的難點在於:當某個複用單元(比如一條中斷的連線)出現「斷肢」時,如何診斷它斷在哪個部件上並修復。這裡 Builder 模式的價值就顯現了——由於組裝過程被拆成一個個明確的步驟,你可以把 P.apply() 這類組裝方法改寫成能定位問題部件的版本,只修復那一塊,而不必重建整個物件。

什麼時候該用 Builder

不是所有物件都值得套 Builder。判斷標準大致有三點:

建構參數多且大部分可選——若只有兩三個必填參數,建構子綽綽有餘。

物件建立後應保持不變——Builder 的價值在於把「可變的設定階段」與「不可變的使用階段」切乾淨。

組裝過程本身有複雜度——需要特定順序、需要跨步驟共享狀態,或不同型別需要不同的組裝邏輯(此時可再往上抽象出 Builder 介面與具體 Builder,也就是抽象 Builder 模式)。

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