編輯:關於 Android 程式設計
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 只負責「要畫什麼」。
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 模式)。
OpenGL ES 繪製圓柱體:光照與紋理
OpenGL ES 繪製圓柱體:光照與紋理 本文以 OpenGL ES 繪製圓柱體為例,說明圓面、側面、法向量與紋理坐標的處理方式。圓柱體看似簡單,但涉及幾何頂點、三角形
Cocos2d-x 移植 Android 常見問題:中文亂碼的成因與解法
Android 平台的版本與裝置碎片化相當嚴重,因此從 Win32 平台移植到 Android 平台時會遇到不少問題。以下是我們歸納的移植過程中常見的狀況之一:中文亂碼。
Android開發中assets目錄資源的完整使用總結
Android資源檔案的分類 Android的資源檔案大致可分為兩類: 第一類是放在res目錄下、可被編譯的資源檔案。系統會在R.java中自動為這類資源產生對應的ID,
Android 應用程式測試實務:從測試專案到 UI 驗證
一、建立測試環境 安裝了 ADT 外掛的 Eclipse 提供圖形化的開發環境,其中一項便利功能是能自動為 Android 應用專案建立對應的測試專案。 第一步,建立一個