Android和設計模式:建造者模式

 
    最近在繼續iPhone 業務的同時還須要從新拾起Android 。在有些生疏的狀況下,決定從Android 源碼中感悟一些Android 的風格和方式。在學習源碼的過程當中也發現了一些通用的模式,但願經過一個系列的文章總結和分享下。

    建造者模式將一個複雜的構建與其表示相分離,使得一樣的構建過程能夠建立不一樣的表示。Android中AlertDialog是一個多面手,能夠有着不一樣的樣式和呈現,這樣經過Builder就能夠有效實現構建和表示的分離。其實現的類圖以下:
clip_p_w_picpath001
主要代碼以下:
public static class Builder {
    private final AlertController.AlertParams P;
    private int mTheme;
    ......
    public Builder(Context context, int theme) {
        P = new AlertController.AlertParams(context);
        mTheme = theme;
    }
    public Builder setTitle(int titleId) {
        P.mTitle = P.mContext.getText(titleId);
        return this;
    }
    public Builder setMessage(int messageId) {
        P.mMessage = P.mContext.getText(messageId);
        return this;
    }
    public Builder setIcon(int iconId) {
        P.mIconId = iconId;
        return this;
    }
    public Builder setPositiveButton(int textId, final OnClickListener listener) {
        P.mPositiveButtonText = P.mContext.getText(textId);
        P.mPositiveButtonListener = listener;
        return this;
    }
    public Builder setNegativeButton(int textId, final OnClickListener listener) {
        P.mNegativeButtonText = P.mContext.getText(textId);
        P.mNegativeButtonListener = listener;
        return this;
    }
    ......
    public AlertDialog create() {
        final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
        P.apply(dialog.mAlert);
        dialog.setCancelable(P.mCancelable);
        dialog.setOnCancelListener(P.mOnCancelListener);
        if (P.mOnKeyListener != null) {
            dialog.setOnKeyListener(P.mOnKeyListener);
        }
        return dialog;
    }
    public AlertDialog show() {
        AlertDialog dialog = create();
        dialog.show();
        return dialog;
    }
}
    其中在進行各類屬性設定的時候都返回this,這樣就能夠實現「流暢的接口」,建立AlertDialog的時候就能夠使用以下代碼: AlertDialog langSelectionDialog = new AlertDialog.Builder(context).setTitle("please select a language").setSingleChoiceItems(     new String[] {"en", "tr"},  0, null).setPositiveButton("ok", new OnClickListener() {                         public void onClick(DialogInterface dialog, int which) {                         Log.i("Tag","ok "+ which);                     }                 }).setNegativeButton("cancle", new OnClickListener() {                     public void onClick(DialogInterface dialog, int which) {                         Log.i("Tag","cancle");                     }                 }).show();
相關文章
相關標籤/搜索