从AlertDialog源码看链式调用

2018-06-11  本文已影响0人  孙大硕

相信我们大家都用过AlertDialog,但是我们没办法去直接实例化一个AlertDialog,因为内部的构造方法都是private,我们只能通过AlertDialog的内部类Builder去生成一个AlertDialog对象,可是为什么要这样设计呢?

看过设计模式的人一眼就会发现,这怎么像传说中的“建造者模式”呢?

建造者解决的问题:是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

这里给出一般的建造者模式模型:

Builder:给出一个抽象接口,以规范产品对象的各个组成成分的建造。这个接口规定要实现复杂对象的哪些部分的创建,并不涉及具体的对象部件的创建。

ConcreteBuilder:实现Builder接口,针对不同的商业逻辑,具体化复杂对象的各部分的创建。 在建造过程完成后,提供产品的实例。

Director:调用具体建造者来创建复杂对象的各个部分,在指导者中不涉及具体产品的信息,只负责保证对象各部分完整创建或按某种顺序创建。

Product:要创建的复杂对象。

下面我们通过一个实例来演示一下:

//我们要创建的复杂的类
class Person{
    private String head;
    public String getHead() {
        return head;
    }
    public void setHead(String head) {
        this.head = head;
    }
    public String getArms() {
        return arms;
    }
    public void setArms(String arms) {
        this.arms = arms;
    }
    private String arms;
    
}
//抽象的建造者
interface Builder{
    void setHead(String head);
    void setArms(String arms);
    
    //得到person实例
    Person getPerson();
}

//建造者的实现类,要有一个Person的实例成员
class Concrete implements Builder{

    Person person=new Person();
    

    @Override
    public Person getPerson() {
        // TODO Auto-generated method stub
        return person;
    }


    @Override
    public void setHead(String head) {
        // TODO Auto-generated method stub
        person.setHead(head);
        
        
    }


    @Override
    public void setArms(String arms) {
        // TODO Auto-generated method stub
        person.setArms(arms);
        
    }
    
}

class Test{
    public static void main(String[] args) {
        Concrete concrete=new Concrete();
        
        concrete.setArms("123");
        concrete.setHead("hhh");
        Person person=concrete.getPerson();
    
    }
}

其实逻辑挺简单的,抽象的建造者要有一个build方法来创建返回我们想要的对象,所以建造者的实现类就必须有一个我们要得到的对象作为变量,建造者的方法也都会调用目标的方法来对目标对象进行构建。

我们说的链式调用其实是建造者模式的升级版,建造者是内部类来实现的。

下面是内部类的形式:

public class Person {
    private Person(Builder builder) {
        arms=builder.arms;
        head=builder.head;
    }
    private String arms;
    public String getArms() {
        return arms;
    }
    public String getHead() {
        return head;
    }
    private String head;
    
    public static class Builder{
         private String arms;
         private String head;
        
        public Builder setArms(String arms) {
            this.arms=arms;
            return this;
        }
        public Builder setHead(String head) {
            this.head=head;
            return this;
        }
        
        public Person build() {
            return new Person(this);
        }
    }
    
}

class Test{
    public static void main(String[] args) {
        Person.Builder builder=new Person.Builder();
        builder.setArms("123");
        builder.setHead("hhh");
        Person person=builder.build();
    }
}

通过这种方式就能进行链式调用了,其实非内部类也能实现,不过那样的可读性不太好,而且对Builder的封装性也不好。

关于AlertDialog

我们平时使用AlertDialog就像下面这样,这是一种典型的内部类形式的建造者模式:

  AlertDialog.Builder builder=new AlertDialog.Builder(this).setTitle("你好").setCancelable(true).
                setIcon(R.mipmap.ic_launcher).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                
            }
        });

        AlertDialog alertDialog= builder.create();

Builder就是一个内部静态类,这是它的构造方法

public static class Builder {

 public Builder(@NonNull Context context) {
            this(context, resolveDialogTheme(context, 0));
        }

public Builder(@NonNull Context context, @StyleRes int themeResId) {
            P = new AlertController.AlertParams(new ContextThemeWrapper(
                    context, resolveDialogTheme(context, themeResId)));
            mTheme = themeResId;
        }

内部封装了很多初始化AlertDialog的方法:

public Builder setTitle(@StringRes int titleId) {
            P.mTitle = P.mContext.getText(titleId);
            return this;
        }
public Builder setCustomTitle(@Nullable View customTitleView) {
            P.mCustomTitleView = customTitleView;
            return this;
        }

  public Builder setMessage(@StringRes int messageId) {
            P.mMessage = P.mContext.getText(messageId);
            return this;
        }

 public Builder setIcon(@DrawableRes int iconId) {
            P.mIconId = iconId;
            return this;
        }

这些方法中都用到了一个实例P,我们来看这个P是什么

 private final AlertController.AlertParams P;

emm,这个P是个什么东西?

我们先来看Builder.create()方法:

public AlertDialog create() {
            // We can't use Dialog's 3-arg constructor with the createThemeContextWrapper param,
            // so we always have to re-set the theme
            final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
            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;
        }

这里就和我们举的那个简单的例子不一样了,这个AlertDialog其实不是直接通过Builder构建的,是通过Builder构建了一个 AlertController.AlertParams,然后在通过这个构建一个AlertDialog

上面的种种方法都显示了这样一个关系。

我们举个例子,比如P.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 || mPositiveButtonIcon != null) {
                dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
                        mPositiveButtonListener, null, mPositiveButtonIcon);
            }
            if (mNegativeButtonText != null || mNegativeButtonIcon != null) {
                dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
                        mNegativeButtonListener, null, mNegativeButtonIcon);
            }
            if (mNeutralButtonText != null || mNeutralButtonIcon != null) {
                dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
                        mNeutralButtonListener, null, mNeutralButtonIcon);
            }
            // 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);
                }
            } else if (mViewLayoutResId != 0) {
                dialog.setView(mViewLayoutResId);
            }

            /*
            dialog.setCancelable(mCancelable);
            dialog.setOnCancelListener(mOnCancelListener);
            if (mOnKeyListener != null) {
                dialog.setOnKeyListener(mOnKeyListener);
            }
            */
        }

其实严格地讲,P的这个方法只是构造了AlertDialog内部的一个参数AlertController mAlert,这个参数才是AlertDialog标题内容等等的载体

AlertController.java

class AlertController {
    private final Context mContext;
    final AppCompatDialog mDialog;
    private final Window mWindow;
    private final int mButtonIconDimen;

    private CharSequence mTitle;
    private CharSequence mMessage;
    ListView mListView;
    private View mView;

    private int mViewLayoutResId;

    private int mViewSpacingLeft;
    private int mViewSpacingTop;
    private int mViewSpacingRight;
    private int mViewSpacingBottom;
    private boolean mViewSpacingSpecified = false;

    Button mButtonPositive;
    private CharSequence mButtonPositiveText;
    Message mButtonPositiveMessage;
    private Drawable mButtonPositiveIcon;

    Button mButtonNegative;
    private CharSequence mButtonNegativeText;
    Message mButtonNegativeMessage;
    private Drawable mButtonNegativeIcon;

    Button mButtonNeutral;
    private CharSequence mButtonNeutralText;
    Message mButtonNeutralMessage;
    private Drawable mButtonNeutralIcon;

    NestedScrollView mScrollView;

    private int mIconId = 0;
    private Drawable mIcon;

    private ImageView mIconView;
    private TextView mTitleView;
    private TextView mMessageView;
    private View mCustomTitleView;

    ListAdapter mAdapter;

    int mCheckedItem = -1;

    private int mAlertDialogLayout;
    private int mButtonPanelSideLayout;
    int mListLayout;
    int mMultiChoiceItemLayout;
    int mSingleChoiceItemLayout;
    int mListItemLayout;

    private boolean mShowTitle;

    private int mButtonPanelLayoutHint = AlertDialog.LAYOUT_HINT_NONE;

    Handler mHandler;
    //省略只看属性
}

我们可以看到,这里面大多的属性都是我们熟知的需要设置的,AlertController就是封装了这些。

好了,这也是第一次这么认真地看源码,很多说的不好的地方请大家见谅,有错误的地方还请大家指点。

我有一个疑问就是,为什么不能直接用一个builder内部类完事儿呢,又引出来这么多的中间变量,只是为了解耦吗,还是有其他的原因,希望能够得到大神指点!

上一篇 下一篇

猜你喜欢

热点阅读