第三章:自由扩建你的项目—Builder模式
模式定义
将模式的构建与表象分离,同样的构建方法可以创建出不同的表象
应用场景
- 不同的方法执行顺序,产生不同的事件结果
- 多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时
- 产品类复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候使用建造者模式非常合适
- 当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值时
在Android中的源码实现
Android中的AlertDialog.Builder就是一个简单的Builder的模式,将诸多参数分离关注点,使用者只需关注title、buttons、message等,将Dialoag的构建与表示分离。
以下代码是AlertDialog的源码:
public class AlertDialog extends AppCompatDialog implements DialogInterface { // 忽略诸多参数 public static class Builder { private final AlertController.AlertParams P; private final int mTheme; 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; } public Builder setTitle(@StringRes int titleId) { P.mTitle = P.mContext.getText(titleId); return this; } public Builder setMessage(@StringRes int messageId) { P.mMessage = P.mContext.getText(messageId); return this; } public AlertDialog create() { // 将P的参数取出,赋值view属性 } // ...忽略构建方法 } public static class AlertParams { //... 忽略其他参数 public CharSequence mTitle; public CharSequence mMessage; } }
总结
优点:
(1)隐藏构建的复杂度,将表现与构建分离,使用者无需关系构建过程 (2)易于扩展,且维护性较低
缺点:
(3)会产生多余Builder和Director对象,消耗内存