Builder建造者模式

Builder建造者模式,主要用于构建一个复杂的对象,将对象的构建与表示分离,在不使用建造者模式的时候,我们构建一个复杂的对象,可能构造方法的参数都很七八个,如果是可选参数,那么可能会重载多个构造方法,当用户使用该类的时候,需要仔细观察,需要哪个构造方法,才能满足需求。使用Builder建造者模式就可以解决这个痛点

一、Android源码之AlertDialog

AlertDialog 内部就是使用的建造者模式,核心类包括如下:

  • AlertDialog
  • AlertDialog.Builder
  • AlertController
  • AlertController.AlertParams

AlertDialog的基本使用:

1
2
3
4
5
6
AlertDialog.Builder(this)//1
.setTitle("标题")//2
.setMessage("消息内容")
.setPositiveButton("确定",null)
.setNegativeButton("取消",null)
.show()//3

分析1:我们知道Builder是AlertDialog的静态内部类,Builder的构造方法需要传入上下文Context,Context主要用于初始化LayoutInflater

1
2
3
4
5
6
7
8
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}

public static class Builder {
private final AlertController.AlertParams P;
}

分析2:可以看到,设置的标题被保存到Builder的变量P中,这个P(AlertParams)的作用就是用于存储整个对话框构建需要的信息

1
2
3
4
5
public AlertDialog show() {
final AlertDialog dialog = create();
dialog.show();
return dialog;
}

分析3:Builder的show方法,内部调用create方法,创建了AlertDialog,最后show出来,看下create方法源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public AlertDialog create() {
// Context has already been wrapped with the appropriate theme.
final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
P.apply(dialog.mAlert);//4
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;
}

分析4:apply()方法就是将存储的所有信息,设置到AlertDialog的AlertController里的控件上去

1
2
3
4
5
6
7
8
9
10
11
public void apply(AlertController dialog) {
if (mTitle != null) {
dialog.setTitle(mTitle);
}
if (mIcon != null) {
dialog.setIcon(mIcon);
}
if (mMessage != null) {
dialog.setMessage(mMessage);
}
}

二、实战Android万能dialog

todo…