Android 設計模式學習之 Builder 模式
建造者模式(Builder Pattern),是創造性模式之一,Builder 模式的目的則是為了將對象的構建與展示分離。Builder 模式是一步一步創建一個復雜對象的創建型模式,它允許用戶在不知道內部構建細節的情況下,可以更精細地控制對象的構造流程。
模式的使用場景
1.相同的方法,不同的執行順序,產生不同的事件結果時;
2.多個部件或零件,都可以裝配到一個對象中,但是產生的運行結果又不相同時;
3.產品類非常復雜,或者產品類中的調用順序不同產生了不同的效能,這個時候使用建造者模式非常合適。
UML類圖
角色介紹
Product 產品類 : 產品的抽象類;
Builder : 抽象類, 規范產品的組建,一般是由子類實現具體的組件過程;
ConcreteBuilder : 具體的構建器;
Director : 統一組裝過程(可省略)。
Builder模式簡單實現
Builder模式最典型的例子,就是組裝電腦的例子了
創建產品類
public class Computer {
private String mCpu;
private String mRam;
public void setmCpu(String mCpu) {
this.mCpu = mCpu;
}
public void setmRam(String mRam) {
this.mRam = mRam;
}
}
創建Builder類組裝電腦有一套組裝方法的模版,就是一個抽象的Builder類,里面提供了安裝CPU、內存的方法,以及組裝成電腦的create方法:
public abstract class Builder {
public abstract void buildCpu(String cpu);
public abstract void buildRam(String ram);
public abstract Computer create();
}
實現了抽象的Builder類,ComputerBuilder類用于組裝電腦:
public class ComputerBuilder extends Builder {
private Computer mComputer = new Computer();
@Override
public void buildCpu(String cpu) {
mComputer.setmCpu(cpu);
}
@Override
public void buildRam(String ram) {
mComputer.setmRam(ram);
}
@Override
public Computer create() {
return mComputer;
}
}
用Dirextor指揮者類來統一組裝過程
public class Direcror {
Builder mBuild=null;
public Direcror(Builder build){
this.mBuild=build;
}
public Computer CreateComputer(String cpu,String mainboard,String ram){
//規范建造流程
this.mBuild.buildMainboard(mainboard);
this.mBuild.buildRam(ram);
return mBuild.create();
}
}
客戶端調用指揮者類
最后商家用指揮者類組裝電腦。我們只需要提供我們想要的CPU,內存就可以了,至于商家怎樣組裝的電腦我們無需知道。
public class CreatComputer {
public static void main(String[]args){
Builder mBuilder=new MoonComputerBuilder();
Direcror mDirecror=new Direcror(mBuilder);
//組裝電腦
mDirecror.CreateComputer("i5-3210","DDR4");
}
}
Android源碼中的Builder模式
在Android源碼中,我們最常用到的Builder模式就是AlertDialog.Builder, 使用該Builder來構建復雜的AlertDialog對象。簡單示例如下 :
//顯示基本的AlertDialog
private void showDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.icon);
builder.setTitle("頭部");
builder.setMessage("內容");
builder.setPositiveButton("Button1",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("點擊了對話框上的Button1");
}
})
.setNeutralButton("Button2",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("點擊了對話框上的Button2");
}
});
builder.create().show(); // 構建AlertDialog, 并且顯示
}
下面我們看看AlertDialog的相關源碼
// AlertDialog
public class AlertDialog extends Dialog implements DialogInterface {
// Controller, 接受Builder成員變量P中的各個參數
private AlertController mAlert;
// 構造函數
protected AlertDialog(Context context, int theme) {
this(context, theme, true);
}
// 4 : 構造AlertDialog
AlertDialog(Context context, int theme, boolean createContextWrapper) {
super(context, resolveDialogTheme(context, theme), createContextWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
mAlert = new AlertController(getContext(), this, getWindow());
}
// 實際上調用的是mAlert的setTitle方法
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
// 實際上調用的是mAlert的setCustomTitle方法
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
// AlertDialog其他的代碼省略
// ************ Builder為AlertDialog的內部類 *******************
public static class Builder {
// 1 : 存儲AlertDialog的各個參數, 例如title, message, icon等.
private final AlertController.AlertParams P;
// 屬性省略
/**
* Constructor using a context for this builder and the {@link AlertDialog} it creates.
*/
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;
}
// Builder的其他代碼省略 ......
// 2 : 設置各種參數
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() {
// 調用new AlertDialog構造對象, 并且將參數傳遞個體AlertDialog
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
// 5 : 將P中的參數應用的dialog中的mAlert對象中
P.apply(dialog.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;
}
}
}
可以看到,通過Builder來設置AlertDialog中的title, message, button等參數, 這些參數都存儲在類型為AlertController.AlertParams的成員變量P中,AlertController.AlertParams中包含了與之對應的成員變量。在調用Builder類的create函數時才創建AlertDialog, 并且將Builder成員變量P中保存的參數應用到AlertDialog的mAlert對象中,即P.apply(dialog.mAlert)代碼段。我們看看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);
}
if (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// For a list, the client can either supply an array of items or an
// adapter or a cursor
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
createListView(dialog);
}
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
} else {
dialog.setView(mView);
}
}
}
實際上就是把P中的參數挨個的設置到AlertController中, 也就是AlertDialog中的mAlert對象。從AlertDialog的各個setter方法中我們也可以看到,實際上也都是調用了mAlert對應的setter方法。在這里,Builder同時扮演了上文中提到的builder、ConcreteBuilder、Director的角色,簡化了Builder模式的設計。
在實際項目中的應用
我們可以采用系統已經提供好的Builder設計模式構建整個應用的萬能Dialog,代碼可以參考系統的AlertDialog
public static class Builder {
private AlertController.AlertParams P;
public Builder(Context context) {
this(context, 0);
}
public Builder(Context context, int themeResId) {
P = new AlertController.AlertParams();
P.themeResId = themeResId;
P.context = context;
}
public Builder setText(int viewId, CharSequence text) {
P.textArray.put(viewId, text);
return this;
}
public Builder setOnClickListener(int viewId, View.OnClickListener listener) {
P.clickArray.put(viewId, listener);
return this;
}
public Builder setContentView(int layoutId) {
P.view = null;
P.layoutId = layoutId;
return this;
}
public Builder setContentView(View view) {
P.layoutId = 0;
P.view = view;
return this;
}
/**
* Sets whether the dialog is cancelable or not. Default is true.
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder setCancelable(boolean cancelable) {
P.cancelable = cancelable;
return this;
}
/**
* Sets the callback that will be called if the dialog is canceled.
* <p>
* <p>Even in a cancelable dialog, the dialog may be dismissed for reasons other than
* being canceled or one of the supplied choices being selected.
* If you are interested in listening for all cases where the dialog is dismissed
* and not just when it is canceled, see
* {@link #setOnDismissListener(OnDismissListener) setOnDismissListener}.</p>
*
* @return This Builder object to allow for chaining of calls to set methods
* @see #setCancelable(boolean)
* @see #setOnDismissListener(OnDismissListener)
*/
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
P.onCancelListener = onCancelListener;
return this;
}
/**
* Sets the callback that will be called when the dialog is dismissed for any reason.
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder setOnDismissListener(OnDismissListener onDismissListener) {
P.onDismissListener = onDismissListener;
return this;
}
/**
* Sets the callback that will be called if a key is dispatched to the dialog.
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder setOnKeyListener(OnKeyListener onKeyListener) {
P.onKeyListener = onKeyListener;
return this;
}
/**
* Creates an {@link AlertDialog} with the arguments supplied to this
* builder.
* <p/>
* Calling this method does not display the dialog. If no additional
* processing is needed, {@link #show()} may be called instead to both
* create and display the dialog.
*/
public BaseDialog create() {
// Context has already been wrapped with the appropriate theme.
final BaseDialog dialog = new BaseDialog(P.context, P.themeResId);
P.apply(dialog.mAlert);
dialog.setCancelable(P.cancelable);
if (P.cancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.onCancelListener);
dialog.setOnDismissListener(P.onDismissListener);
if (P.onKeyListener != null) {
dialog.setOnKeyListener(P.onKeyListener);
}
return dialog;
}
/**
* Creates an {@link AlertDialog} with the arguments supplied to this
* builder and immediately displays the dialog.
* <p/>
* Calling this method is functionally identical to:
* <pre>
* AlertDialog dialog = builder.create();
* dialog.show();
* </pre>
*/
public BaseDialog show() {
final BaseDialog dialog = create();
dialog.show();
return dialog;
}
}
class AlertController {
private DialogViewHelper mViewHelper;
private BaseDialog mDialog;
private Window mWindow;
public AlertController(BaseDialog dialog, Window window) {
mDialog = dialog;
mWindow = window;
}
/**
* 獲取Dialog
* @return
*/
public BaseDialog getDialog() {
return mDialog;
}
/**
* 獲取window
* @return
*/
public Window getWindow() {
return mWindow;
}
public DialogViewHelper getViewHelper() {
return mViewHelper;
}
/**
* 設置View的輔助
* @param viewHelper
*/
public void setDialogViewHelper(DialogViewHelper viewHelper) {
this.mViewHelper = viewHelper;
}
/**
* 設置文本
* @param viewId
* @param text
*/
public void setText(int viewId, CharSequence text) {
mViewHelper.setText(viewId, text);
}
/**
* 設置點擊事件
* @param viewId
* @param listener
*/
public void setOnClickListener(int viewId, View.OnClickListener listener) {
mViewHelper.setOnClickListener(viewId, listener);
}
/**
* 通過id獲取View
* @param viewId
* @param <T>
* @return
*/
public <T extends View> T getView(int viewId) {
return mViewHelper.getView(viewId);
}
}
代碼調用
@Override
public void onClick(View v) {
BaseDialog dialog = new BaseDialog.Builder(this)
.setContentView(R.layout.detail_dialog).fullWith()
.fromBottom(false)
.show();
}
最后總結一下Buider模式的優缺點:
Builder 模式的優點:
1.將一個復雜對象的創建過程封裝起來,使得客戶端不必知道產品內部組成的細節;
2.允許對象通過多個步驟來創建,并且可以改變過程和選擇需要的過程;
3.產品的實現可以被替換,因為客戶端只看到一個抽象的接口;
創建者獨立,容易擴展。
Builder 模式缺點:
1.會產生多余的 Builder 對象以及 Director 對象,消耗內存;
2.與工廠模式相比,采用 Builder 模式創建對象的客戶,需要具備更多的領域知識。
來自:http://blog.csdn.net/u012124438/article/details/59777619