Android設(shè)計(jì)模式(二)- Builder模式

目錄

  1. 定義
  2. 使用場景
  3. UML類圖
  4. 簡單實(shí)現(xiàn)
  5. Android源碼中的Builder模式實(shí)現(xiàn)
  6. AlertDialog源碼
  7. 創(chuàng)建AlertDialog
  8. 顯示AlertDialog
  9. 總結(jié)
  10. 優(yōu)點(diǎn)
  11. 缺點(diǎn)

博客地址
Builder模式是一步一步創(chuàng)建復(fù)雜對象的創(chuàng)建型模式。允許用戶在不知道內(nèi)部構(gòu)建細(xì)節(jié)的情況下,可以更精細(xì)的控制構(gòu)造流程。該模式是為了將構(gòu)建過程和表示分開,使構(gòu)建過程和部件都可以自由擴(kuò)展,兩者的耦合度也降到最低。

定義

將一個(gè)復(fù)雜對象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示。

使用場景

  • 相同的方法,不同的執(zhí)行順序,產(chǎn)生不同的結(jié)果。
  • 多個(gè)部件或零件都可以裝配到一個(gè)對象中,但產(chǎn)生的運(yùn)行結(jié)果又不相同時(shí)。
  • 產(chǎn)品類非常復(fù)雜,或者構(gòu)建部件的順序不同產(chǎn)生了不同的作用。
  • 當(dāng)初始化一個(gè)對象特別復(fù)雜時(shí),如參數(shù)特別多且很多參數(shù)都有默認(rèn)值的時(shí)

UML類圖


角色介紹:

  • Product 產(chǎn)品的抽象類
  • Builder 抽象的Builder類,規(guī)范產(chǎn)品的組建,一般由子類實(shí)現(xiàn)具體的構(gòu)建過程
  • ConcreteBuilder 具體的Builder類
  • Director 統(tǒng)一組裝類,導(dǎo)演類

簡單實(shí)現(xiàn)

書中以計(jì)算機(jī)舉了個(gè)例子

  • 先創(chuàng)建計(jì)算機(jī)的抽象類
public abstract class Computer {
    /**
     * 主板
     */
    protected String mBoard;
    /**
     * 顯示器
     */
    protected String mDisplay;
    /**
     * 系統(tǒng)
     */
    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 + '\'' +
                '}';
    }
}
  • 創(chuàng)建計(jì)算機(jī)的一個(gè)實(shí)現(xiàn)類 蘋果計(jì)算機(jī)
public class Macbook extends Computer {
    public Macbook() {
    }

    @Override
    public void setmOS() {
        mOS="macOS";
    }
}
  • 創(chuàng)建builder的抽象類,規(guī)范產(chǎn)品的組建
public abstract class Builder {
    public abstract Builder buildBoard(String board);
    public abstract Builder buildDisplay(String display);
    public abstract Builder buildOS();
    public abstract Computer create();
}
  • 創(chuàng)建具體的Builder類,實(shí)現(xiàn)蘋果計(jì)算機(jī)的組裝
public class MacbookBuilder extends Builder {
    private Computer mComputer = new Macbook();
//這里的方法返回builder本身,可以鏈?zhǔn)秸{(diào)用
    @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;
    }

//調(diào)用這個(gè)方法生成最終的產(chǎn)品

    @Override
    public Computer create() {
        return mComputer;
    }
}
  • 導(dǎo)演類
public class Director {
    Builder mBuilder = null;

    public Director(Builder mBuilder) {
        this.mBuilder = mBuilder;
    }
//使用導(dǎo)演類的話只要傳參數(shù)就行,然后用傳入的builder創(chuàng)建產(chǎn)品。
    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();
//不適用導(dǎo)演類直接創(chuàng)建,通常都用這樣的方式
        Computer computer =builder.buildBoard("huashuo")
                .buildOS()
                .buildDisplay("sanxing")
                .create();
        System.out.println(computer.toString());
//使用導(dǎo)演類創(chuàng)建
        Director director = new Director(builder);
        director.construct("weixing","dell");
        Computer computer1 = builder.create();
        System.out.println(computer1);
    }
}

-打印結(jié)果

Computer{mBoard='huashuo', mDisplay='sanxing', mOS='macOS'}
Computer{mBoard='weixing', mDisplay='dell', mOS='macOS'}

Android源碼中的Builder模式實(shí)現(xiàn)

我們在構(gòu)建對話框的時(shí)候通常都是以下的用法:

private void showDialog(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(R.mipmap.ic_launcher)
                .setTitle("標(biāo)題")
                .setMessage("哈哈哈的信息")
                .setPositiveButton("按鈕1", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(context,"點(diǎn)了按鈕1",Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("按鈕2", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(context,"點(diǎn)了按鈕2",Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("按鈕3", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(context,"點(diǎn)了按鈕3",Toast.LENGTH_SHORT).show();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

可以看出AlertDialog就是通過AlertDialog.Builder來構(gòu)建的。

AlertDialog源碼:

看著源碼來分析

創(chuàng)建AlertDialog

public class AlertDialog extends Dialog implements DialogInterface {
    //留意這個(gè)變量
    private AlertController mAlert;
    //不公開構(gòu)造方法,外部無法直接實(shí)例化
    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();
    }
//......省略代碼
    //這個(gè)是AlertDialog的內(nèi)部類 AlertDialog.Builder
    public static class Builder {
        //這里面有一個(gè)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() {
            // 這里創(chuàng)建了一個(gè)AlertDialog
            final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
            //通過這個(gè)方法,把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方法設(shè)置一些屬性的時(shí)候,builder吧這些設(shè)置都存在一個(gè)變量P中,這個(gè)P在Builder創(chuàng)建時(shí)在構(gòu)造方法中初始化,類型是AlertController.AlertParams,是AlertController的內(nèi)部類。

然后在Builder的create方法中,new一個(gè)新的AlertDialog,并在AlertDialog的構(gòu)造方法中初始化了AlertDialog的變量mAlert,類型是AlertController。
調(diào)用P.apply(mAlert)方法把P中保存的參數(shù)傳遞給AlertDialog的變量mAlert。最后返回這個(gè)生成的AlertDialog。
看一下這個(gè)方法:

package com.android.internal.app;
public class AlertController {
    public static class AlertParams {
        public void apply(AlertController dialog) {
//基本上所有的方法都是把自己的參數(shù)設(shè)置給傳進(jìn)來的dialog。
            if (mCustomTitleView != null) {
                dialog.setCustomTitle(mCustomTitleView);
            } else {
                if (mTitle != null) {
                    dialog.setTitle(mTitle);
                }
               ......
            }
            if (mMessage != null) {
                dialog.setMessage(mMessage);
            }
            ......
        }
    }
}

顯示AlertDialog

在上面的使用例子中可以看出,獲取到Dialog后,直接調(diào)用alertDialog.show()就能顯示AlertDialog了。

package android.app;
public class Dialog implements DialogInterface, Window.Callback,
        KeyEvent.Callback, OnCreateContextMenuListener, Window.OnWindowDismissedCallback {
    public void show() {
//如果已經(jīng)顯示,就直接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;
//如果沒有創(chuàng)建,就執(zhí)行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();
        ......
//獲取布局參數(shù)
        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和布局參數(shù)添加到WindowManager中
        mWindowManager.addView(mDecor, l);
        mShowing = true;
//向Handler發(fā)送一個(gè)Dialog的消息,從而顯示AlertDialog
        sendShowMessage();
    }
}

簡單分析一下這個(gè)方法的主要流程就是:
(1)先確認(rèn)AlertDialog的onCreate方法是否執(zhí)行,如果沒有執(zhí)行就調(diào)用dispatchOnCreate(null)方法來調(diào)用AlertDialog的onCreate方法。
(2)調(diào)用Dialog的onStart()方法。
(3)將設(shè)置好的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() {
//獲取相應(yīng)的對話框內(nèi)容的布局
        int contentView = selectContentView();
//將布局調(diào)用Window.setContentView設(shè)置布局。
        mWindow.setContentView(contentView);
        setupView();
    }
}

分析LayoutInflater時(shí)就知道,Activity的setContentView最后也是調(diào)用了Window.setContentView這個(gè)方法。所以這個(gè)方法里主要就是給對話框設(shè)置布局。

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,那么這個(gè)布局是什么時(shí)候初始化的呢?
在AlertController的構(gòu)造方法中可以看見:

    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();

        /* 因?yàn)橛米远x的標(biāo)題欄,所以要隱藏DecorView的Title布局 */
        window.requestFeature(Window.FEATURE_NO_TITLE);
    }

好,來看一下布局文件,也就是alert_dialog.xml
默認(rèn)的布局是這樣的,本來文件中是空白的,為了能看出來,我給布局設(shè)置了一些值和背景色:


系統(tǒng)默認(rèn)的dialog布局
系統(tǒng)默認(rèn)的dialog布局

源代碼貼出來,可以自己試試:

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);
       ......
        // 這里看有沒有設(shè)置自定義布局
        final ViewGroup customPanel = (ViewGroup) parentPanel.findViewById(R.id.customPanel);
        setupCustomContent(customPanel);
........
 
//根據(jù)傳入的參數(shù)來設(shè)置布局里面的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);
//所有的布局設(shè)置為背景
        setBackground(a, topPanel, contentPanel, customPanel, buttonPanel,
                hasTopPanel, hasCustomPanel, hasButtonPanel);
        a.recycle();
    }

所以setupView的流程就是:
(1)初始化AlertDialog布局中的各個(gè)部分
(2)布局全部設(shè)置完畢后,又通過Window對象關(guān)聯(lián)到DecorView。并將DecorView添加到用戶窗口上顯示出來。

總結(jié)

優(yōu)點(diǎn)

  • 良好的封裝性,使用Builder模式可以使客戶端不必知道產(chǎn)品的內(nèi)部組成的細(xì)節(jié)
  • builder獨(dú)立,容易擴(kuò)展

缺點(diǎn)

  • 會產(chǎn)生多余的Builder對象以及Director對象(用的不多),消耗內(nèi)存
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 面向?qū)ο蟮牧笤瓌t 單一職責(zé)原則 所謂職責(zé)是指類變化的原因。如果一個(gè)類有多于一個(gè)的動(dòng)機(jī)被改變,那么這個(gè)類就具有多于...
    JxMY閱讀 1,028評論 1 3
  • 前言:這個(gè)過程中遇到了兩個(gè)問題,都比較基礎(chǔ),第一個(gè)問題是:系統(tǒng)無法識別圖片資源,不過還好,被我刪了之后就很好的運(yùn)行...
    九尾74閱讀 3,154評論 0 6
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,628評論 19 139
  • 1 場景問題# 1.1 繼續(xù)導(dǎo)出數(shù)據(jù)的應(yīng)用框架## 在討論工廠方法模式的時(shí)候,提到了一個(gè)導(dǎo)出數(shù)據(jù)的應(yīng)用框架。 對于...
    七寸知架構(gòu)閱讀 6,155評論 1 64
  • 生命,不只是呼吸,它不只是氧氣。還有些別的東西在,生命本身每一個(gè)獨(dú)一無二的生命經(jīng)驗(yàn),都是愛的不同層面、不同方...
    Yiruna_angel閱讀 1,517評論 0 0

友情鏈接更多精彩內(nèi)容