目錄
- 定義
- 使用場景
- UML類圖
- 簡單實現
- Android源碼中的Builder模式實現
- AlertDialog源碼
- 創建AlertDialog
- 顯示AlertDialog
- 總結
- 優點
- 缺點
博客地址
Builder模式是一步一步創建復雜對象的創建型模式。允許用戶在不知道內部構建細節的情況下,可以更精細的控制構造流程。該模式是為了將構建過程和表示分開,使構建過程和部件都可以自由擴展,兩者的耦合度也降到最低。
定義
將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示。
使用場景
- 相同的方法,不同的執行順序,產生不同的結果。
- 多個部件或零件都可以裝配到一個對象中,但產生的運行結果又不相同時。
- 產品類非常復雜,或者構建部件的順序不同產生了不同的作用。
- 當初始化一個對象特別復雜時,如參數特別多且很多參數都有默認值的時
UML類圖

角色介紹:
- Product 產品的抽象類
- Builder 抽象的Builder類,規范產品的組建,一般由子類實現具體的構建過程
- ConcreteBuilder 具體的Builder類
- Director 統一組裝類,導演類
簡單實現
書中以計算機舉了個例子
- 先創建計算機的抽象類
public abstract class Computer {
/**
* 主板
*/
protected String mBoard;
/**
* 顯示器
*/
protected String mDisplay;
/**
* 系統
*/
protected String mOS;
protected Computer() {
}
public void setmBoard(String mBoard) {
this.mBoard = mBoard;
}
public void setmDisplay(String mDisplay) {
this.mDisplay = mDisplay;
}
public abstract void setmOS();
@Override
public String toString() {
return "Computer{" +
"mBoard='" + mBoard + '\'' +
", mDisplay='" + mDisplay + '\'' +
", mOS='" + mOS + '\'' +
'}';
}
}
- 創建計算機的一個實現類 蘋果計算機
public class Macbook extends Computer {
public Macbook() {
}
@Override
public void setmOS() {
mOS="macOS";
}
}
- 創建builder的抽象類,規范產品的組建
public abstract class Builder {
public abstract Builder buildBoard(String board);
public abstract Builder buildDisplay(String display);
public abstract Builder buildOS();
public abstract Computer create();
}
- 創建具體的Builder類,實現蘋果計算機的組裝
public class MacbookBuilder extends Builder {
private Computer mComputer = new Macbook();
//這里的方法返回builder本身,可以鏈式調用
@Override
public Builder buildBoard(String board) {
mComputer.setmBoard(board);
return this;
}
@Override
public Builder buildDisplay(String display) {
mComputer.setmDisplay(display);
return this;
}
@Override
public Builder buildOS() {
mComputer.setmOS();
return this;
}
//調用這個方法生成最終的產品
@Override
public Computer create() {
return mComputer;
}
}
- 導演類
public class Director {
Builder mBuilder = null;
public Director(Builder mBuilder) {
this.mBuilder = mBuilder;
}
//使用導演類的話只要傳參數就行,然后用傳入的builder創建產品。
public void construct(String board,String display){
mBuilder.buildBoard(board);
mBuilder.buildDisplay(display);
mBuilder.buildOS();
}
}
-使用示例
public class MainM {
public static void main(String[] args) {
Builder builder = new MacbookBuilder();
//不適用導演類直接創建,通常都用這樣的方式
Computer computer =builder.buildBoard("huashuo")
.buildOS()
.buildDisplay("sanxing")
.create();
System.out.println(computer.toString());
//使用導演類創建
Director director = new Director(builder);
director.construct("weixing","dell");
Computer computer1 = builder.create();
System.out.println(computer1);
}
}
-打印結果
Computer{mBoard='huashuo', mDisplay='sanxing', mOS='macOS'}
Computer{mBoard='weixing', mDisplay='dell', mOS='macOS'}
Android源碼中的Builder模式實現
我們在構建對話框的時候通常都是以下的用法:
private void showDialog(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("標題")
.setMessage("哈哈哈的信息")
.setPositiveButton("按鈕1", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context,"點了按鈕1",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("按鈕2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context,"點了按鈕2",Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("按鈕3", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context,"點了按鈕3",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

可以看出AlertDialog就是通過AlertDialog.Builder來構建的。
AlertDialog源碼:
看著源碼來分析
創建AlertDialog
public class AlertDialog extends Dialog implements DialogInterface {
//留意這個變量
private AlertController mAlert;
//不公開構造方法,外部無法直接實例化
protected AlertDialog(Context context) {
this(context, 0);
}
//......省略
AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
super(context, createContextThemeWrapper ? resolveDialogTheme(context, themeResId) : 0,
createContextThemeWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
//初始化mAlert
mAlert = AlertController.create(getContext(), this, getWindow());
}
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
//......省略很多這樣的代碼
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
//......省略代碼
//這個是AlertDialog的內部類 AlertDialog.Builder
public static class Builder {
//這里面有一個AlertController.AlertParams, P
private final AlertController.AlertParams P;
public Builder(Context context, int themeResId) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, themeResId)));
}
//......省略代碼
public Context getContext() {
return P.mContext;
}
public Builder setTitle(@StringRes int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
//......省略很多這樣的代碼
public AlertDialog create() {
// 這里創建了一個AlertDialog
final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
//通過這個方法,把P中的變量傳給AlertDialog的mAlert。
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
dialog.setOnDismissListener(P.mOnDismissListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
//顯示Dialog
public AlertDialog show() {
final AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
}
在源碼中可以看出,我們通過builder的各種setxxx方法設置一些屬性的時候,builder吧這些設置都存在一個變量P中,這個P在Builder創建時在構造方法中初始化,類型是AlertController.AlertParams,是AlertController的內部類。
然后在Builder的create方法中,new一個新的AlertDialog,并在AlertDialog的構造方法中初始化了AlertDialog的變量mAlert,類型是AlertController。
調用P.apply(mAlert)方法把P中保存的參數傳遞給AlertDialog的變量mAlert。最后返回這個生成的AlertDialog。
看一下這個方法:
package com.android.internal.app;
public class AlertController {
public static class AlertParams {
public void apply(AlertController dialog) {
//基本上所有的方法都是把自己的參數設置給傳進來的dialog。
if (mCustomTitleView != null) {
dialog.setCustomTitle(mCustomTitleView);
} else {
if (mTitle != null) {
dialog.setTitle(mTitle);
}
......
}
if (mMessage != null) {
dialog.setMessage(mMessage);
}
......
}
}
}
顯示AlertDialog
在上面的使用例子中可以看出,獲取到Dialog后,直接調用alertDialog.show()就能顯示AlertDialog了。
package android.app;
public class Dialog implements DialogInterface, Window.Callback,
KeyEvent.Callback, OnCreateContextMenuListener, Window.OnWindowDismissedCallback {
public void show() {
//如果已經顯示,就直接return
if (mShowing) {
if (mDecor != null) {
if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
}
mDecor.setVisibility(View.VISIBLE);
}
return;
}
mCanceled = false;
//如果沒有創建,就執行Dialog的onCreate方法
if (!mCreated) {
dispatchOnCreate(null);
} else {
// Fill the DecorView in on any configuration changes that
// may have occured while it was removed from the WindowManager.
final Configuration config = mContext.getResources().getConfiguration();
mWindow.getDecorView().dispatchConfigurationChanged(config);
}
onStart();
//獲取DecorView
mDecor = mWindow.getDecorView();
......
//獲取布局參數
WindowManager.LayoutParams l = mWindow.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
nl.copyFrom(l);
nl.softInputMode |= WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
l = nl;
}
//將DecorView和布局參數添加到WindowManager中
mWindowManager.addView(mDecor, l);
mShowing = true;
//向Handler發送一個Dialog的消息,從而顯示AlertDialog
sendShowMessage();
}
}
簡單分析一下這個方法的主要流程就是:
(1)先確認AlertDialog的onCreate方法是否執行,如果沒有執行就調用dispatchOnCreate(null)方法來調用AlertDialog的onCreate方法。
(2)調用Dialog的onStart()方法。
(3)將設置好的DecorView添加到WindowManager中。
在AlertDialog的onCreate方法中只有兩行代碼:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
mAlert就是AlertDialog的AlertController類型的變量。
package com.android.internal.app;
public class AlertController {
public void installContent() {
//獲取相應的對話框內容的布局
int contentView = selectContentView();
//將布局調用Window.setContentView設置布局。
mWindow.setContentView(contentView);
setupView();
}
}
分析LayoutInflater時就知道,Activity的setContentView最后也是調用了Window.setContentView這個方法。所以這個方法里主要就是給對話框設置布局。
private int selectContentView() {
if (mButtonPanelSideLayout == 0) {
return mAlertDialogLayout;
}
if (mButtonPanelLayoutHint == AlertDialog.LAYOUT_HINT_SIDE) {
return mButtonPanelSideLayout;
}
// TODO: use layout hint side for long messages/lists
return mAlertDialogLayout;
}
看到通過selectContentView()獲得的布局是mAlertDialogLayout,那么這個布局是什么時候初始化的呢?
在AlertController的構造方法中可以看見:
protected AlertController(Context context, DialogInterface di, Window window) {
mContext = context;
mDialogInterface = di;
mWindow = window;
mHandler = new ButtonHandler(di);
final TypedArray a = context.obtainStyledAttributes(null,
R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
//這里可以看處mAlertDialogLayout的布局文件是R.layout.alert_dialog文件。
mAlertDialogLayout = a.getResourceId(
R.styleable.AlertDialog_layout, R.layout.alert_dialog);
......
mShowTitle = a.getBoolean(R.styleable.AlertDialog_showTitle, true);
a.recycle();
/* 因為用自定義的標題欄,所以要隱藏DecorView的Title布局 */
window.requestFeature(Window.FEATURE_NO_TITLE);
}
好,來看一下布局文件,也就是alert_dialog.xml
默認的布局是這樣的,本來文件中是空白的,為了能看出來,我給布局設置了一些值和背景色:

源代碼貼出來,可以自己試試:
alert_dialog.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="9dip"
android:paddingBottom="3dip"
android:paddingStart="3dip"
android:paddingEnd="1dip">
<LinearLayout android:id="@+id/topPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="54dip"
android:orientation="vertical">
<LinearLayout android:id="@+id/title_template"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dip"
android:layout_marginBottom="9dip"
android:layout_marginStart="10dip"
android:layout_marginEnd="10dip">
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="6dip"
android:paddingEnd="10dip"
android:src="@drawable/ic_dialog_info" />
<com.android.internal.widget.DialogTitle android:id="@+id/alertTitle"
style="?android:attr/textAppearanceLarge"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="viewStart" />
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="match_parent"
android:layout_height="1dip"
android:visibility="gone"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
android:src="@android:drawable/divider_horizontal_dark" />
<!-- If the client uses a customTitle, it will be added here. -->
</LinearLayout>
<LinearLayout android:id="@+id/contentPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<ScrollView android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="12dip"
android:paddingStart="14dip"
android:paddingEnd="10dip"
android:overScrollMode="ifContentScrolls">
<TextView android:id="@+id/message"
style="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dip" />
</ScrollView>
</LinearLayout>
<FrameLayout android:id="@+id/customPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<FrameLayout android:id="@+android:id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip" />
</FrameLayout>
<LinearLayout android:id="@+id/buttonPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="54dip"
android:orientation="vertical" >
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="4dip"
android:paddingStart="2dip"
android:paddingEnd="2dip"
android:measureWithLargestChild="true">
<LinearLayout android:id="@+id/leftSpacer"
android:layout_weight="0.25"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" />
<Button android:id="@+id/button1"
android:layout_width="0dip"
android:layout_gravity="start"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<Button android:id="@+id/button3"
android:layout_width="0dip"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<Button android:id="@+id/button2"
android:layout_width="0dip"
android:layout_gravity="end"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<LinearLayout android:id="@+id/rightSpacer"
android:layout_width="0dip"
android:layout_weight="0.25"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
回到AlertController的installContent()方法中,看下一行代碼setupView();
private void setupView() {
//獲取alert_dialog.xml中的布局
final View parentPanel = mWindow.findViewById(R.id.parentPanel);
final View defaultTopPanel = parentPanel.findViewById(R.id.topPanel);
......
// 這里看有沒有設置自定義布局
final ViewGroup customPanel = (ViewGroup) parentPanel.findViewById(R.id.customPanel);
setupCustomContent(customPanel);
........
//根據傳入的參數來設置布局里面的View的顯示或隱藏
if (!hasButtonPanel) {
if (contentPanel != null) {
final View spacer = contentPanel.findViewById(R.id.textSpacerNoButtons);
if (spacer != null) {
spacer.setVisibility(View.VISIBLE);
}
}
mWindow.setCloseOnTouchOutsideIfNotSet(true);
}
.........
final TypedArray a = mContext.obtainStyledAttributes(
null, R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
//所有的布局設置為背景
setBackground(a, topPanel, contentPanel, customPanel, buttonPanel,
hasTopPanel, hasCustomPanel, hasButtonPanel);
a.recycle();
}
所以setupView的流程就是:
(1)初始化AlertDialog布局中的各個部分
(2)布局全部設置完畢后,又通過Window對象關聯到DecorView。并將DecorView添加到用戶窗口上顯示出來。
總結
優點
- 良好的封裝性,使用Builder模式可以使客戶端不必知道產品的內部組成的細節
- builder獨立,容易擴展
缺點
- 會產生多余的Builder對象以及Director對象(用的不多),消耗內存