一 定义
将一个复杂对象的构建和它的表示分离,使同样的构建构成可以创建不同的表示。
建造者模式也是属于创建型模型,是23种GOF之一。
从定义可以看出,建造者模式适用于一个复杂的对象的建造,而且在建造的过程中,客户端不必知道产品内部组成的细节。
二 使用场景
建造者模式适用于一个具有较多的零件的复杂产品的创建过程,由于需求的变化,组成这个复杂产品的各个零件经常猛烈变化,但是它们的组合方式却相对稳定。
建造者模式适用于以下几种场景:
- 1相同的方法,不同的执行顺序,产生不同的结果时
- 2 多个部件或零件,都可以装配到一个对象中,但是产生的结果又不相同。
- 3 产品类非常复杂,或者产品类中的调用顺序不同产生不同的作用。
- 4 当初始化一个对象特别复杂,参数多,而且很多参数都具有默认值时。
三 模式结构
建造者模式主要有四个角色
- Product:要创建的产品类对象
- Builder:建造者的抽象类,规范产品对象的各个组成部分的建造,一般由子类实现具体的建造过程。
- ConcreteBuilder:具体的Builder类,根据不同的业务逻辑,具体化对象的各个组成部分的创建。
- Director:调用具体的建造者,来创建对象的各个部分,在指导者中不涉及具体产品的信息,只负责保证对象各部分完整创建或按某种顺序创建。
四 模拟场景
我们以计算机的组装过程为例,使用建造者模式,首先我们简化计算机的组装过程,这里只考虑三个主要部件,分别为主板,显示器和操作系统,任何计算机都是有以上三个部分组成的。
1 首先定义产品类
我们以MacBook产品为例
/*
* 产品类,Product角色
* @author Jackson
* @version 1.0.0
* since 2018 12 24
*/
public class MacBook {
private String mBoard;
private String mDisplay;
private String mOs;
public String getBoard() {
return mBoard;
}
public void setBoard(String board) {
mBoard = board;
}
public String getDisplay() {
return mDisplay;
}
public void setDisplay(String display) {
mDisplay = display;
}
public String getOs() {
return mOs;
}
public void setOs(String os) {
mOs = os;
}
@Override
public String toString() {
return "MacBook:" + "mBoard=" + mBoard + ",mDisplay=" + mDisplay + ",mOs=" + mOs;
}
}
2 构建抽象的Builder类
抽象的Builder类主要是建造MacBook产品的各个组成部分,并返回MacBook产品。
/*
* 抽象Builder类
* @author Jackson
* @version 1.0.0
* since 2018 12 24
*/
public abstract class Builder {
// 设置主板
public abstract void builderBoard(String board);
// 设置显示器
public abstract void builderDisplay(String display);
// 设置操作系统
public abstract void builderOs(String os);
// 创建Computer
public abstract MacBook getComputer();
}
3 具体的Builder类
具体实例化各个部分的创建
/*
* 具体的Builder类
* @author Jackson
* @version 1.0.0
* since 2018 12 24
*/
public class MacbookBulder extends Builder{
private MacBook mMacBook=new MacBook();
@Override
public void builderBoard(String board) {
mMacBook.setBoard(board);
}
@Override
public void builderDisplay(String display) {
mMacBook.setDisplay(display);
}
@Override
public void builderOs(String os) {
mMacBook.setOs(os);
}
@Override
public MacBook getComputer() {
return mMacBook;
}
}
4 Director类
Director类的主要作用是调用具体的builder,来构建对象的各个部分,Director类起到封装作用,避免高层模块深入到建造者内部的实现类。
public class Director {
Builder mBuilder=null;
public Director(Builder builder){
this.mBuilder=builder;
}
public void constract(String board,String display,String os){
mBuilder.builderBoard(board);
mBuilder.builderDisplay(display);
mBuilder.builderOs(os);
}
}
5 客户端代码
Builder builder=new MacbookBulder();
Director director=new Director(builder);
director.constract("英特尔主板","Retina显示器","Mac OS X系统");
System.out.println(builder.getComputer().toString());
从上面的代码可以看到,MacBook产品是通过MacBookBuilder构建的,Director封装了构建复杂产品对象的过程,对外隐藏了构建细节。Builder和Director一起将一个复杂的对象的构建与表示分离。
实际在开发中,Director常常被忽略,而是直接通过Builder的方式链式组装,同是,builder是一个静态内部类。
public class ThinkPad {
private String mBoard;
private String mDisplay;
private String mOs;
private ThinkPad(Builder builder){
this.mBoard=builder.mBoard;
this.mDisplay=builder.mDisplay;
this.mOs=builder.mOs;
}
public String getBoard() {
return mBoard;
}
public String getDisplay() {
return mDisplay;
}
public String getOs() {
return mOs;
}
static class Builder{
private String mBoard;
private String mDisplay;
private String mOs;
public Builder setBoard(String board){
this.mBoard=board;
return this;
}
public Builder setDisplay(String display){
this.mDisplay=display;
return this;
}
public Builder setOs(String os){
this.mOs=os;
return this;
}
public ThinkPad builder(){
return new ThinkPad(this);
}
}
}
客户端通过链式调用组装方法。
ThinkPad thinkPad=
new ThinkPad.Builder().setBoard("Intel").setDisplay("JDI").setOs("Windows 10").builder();
System.out.println("ThinkPad:"+"board="+thinkPad.getBoard()+"
display="+thinkPad.getDisplay()+" os="+thinkPad.getOs());
在Android中,最常用的使用了Builder模式的事AlertDialog,AlertDialog的是哦用那个方法如下:
new AlertDialog.Builder(this)
.setIcon(R.mipmap.ic_launcher)
.setTitle("Title")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
查看AlertDialog的源码可以看到,
package android.support.v7.app;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.ArrayRes;
import android.support.annotation.AttrRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v7.appcompat.R;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
public class AlertDialog extends AppCompatDialog implements DialogInterface {
final AlertController mAlert;
/**
* No layout hint.
*/
static final int LAYOUT_HINT_NONE = 0;
/**
* Hint layout to the side.
*/
static final int LAYOUT_HINT_SIDE = 1;
/**
* 构造方法
*/
protected AlertDialog(@NonNull Context context) {
this(context, 0);
}
protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) {
super(context, resolveDialogTheme(context, themeResId));
mAlert = new AlertController(getContext(), this, getWindow());
}
protected AlertDialog(@NonNull Context context, boolean cancelable,
@Nullable OnCancelListener cancelListener) {
this(context, 0);
setCancelable(cancelable);
setOnCancelListener(cancelListener);
}
.............................省略..........
---------------------------------- 获取属性 -------------------------------------------------
public Button getButton(int whichButton) {
return mAlert.getButton(whichButton);
}
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
public void setView(View view) {
mAlert.setView(view);
}
.............................省略..........
---------------------------------- 内部静态builder ------------------------------------------------
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;
}
@NonNull
public Context getContext() {
return P.mContext;
}
.............................省略..........
---------------------------------- 设置属性 -------------------------------------------------
public Builder setTitle(@StringRes int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
public Builder setTitle(@Nullable CharSequence title) {
P.mTitle = title;
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 setMessage(@Nullable CharSequence message) {
P.mMessage = message;
return this;
}
.............................省略..........
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;
}
public AlertDialog show() {
final AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
}