前言
在使用一些熱門第三方架構的時候,我們往往會發現,比如okHttp的client,初始化retrofit 對象,初始化 glide 對象等等,都用了這樣:
Retrofit.Builder()
.baseUrl(baseUrl)
.client(getClient())
.addConverterFactory(FastJsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
如此簡潔明了的使用方式,如此靈活多變的鍊式調用,它的具體思想是怎樣的呢,來一起掀起它的神秘面紗
介紹
定義
造者模式(Builder Pattern):将一個複雜對象的建構與它的表示分離,使得同樣的建構過程可以建立不同的表示。
建造者模式是一步一步建立一個複雜的對象,它允許使用者隻通過指定複雜對象的類型和内容就可以建構它們,使用者不需要知道内部的具體建構細節。建造者模式屬于對象建立型模式。根據中文翻譯的不同,建造者模式又可以稱為生成器模式。
主要作用
在使用者不知道對象的建造過程和細節的情況下就可以直接建立複雜的對象。
- 使用者隻需要給出指定複雜對象的類型和内容;
- 建造者模式負責按順序建立複雜對象(把内部的建造過程和細節隐藏起來)
解決的問題
- 友善使用者建立複雜的對象(不需要知道實作過程)
- 代碼複用性 & 封裝性(将對象建構過程和細節進行封裝 & 複用)
模式原理

- 指揮者(Director)直接和客戶(Client)進行需求溝通;
- 溝通後指揮者将客戶建立産品的需求劃分為各個部件的建造請求(Builder);
- 将各個部件的建造請求委派到具體的建造者(ConcreteBuilder);
- 各個具體建造者負責進行産品部件的建構;
- 最終建構成具體産品(Product)。
優缺點
優點
-
易于解耦
将産品本身與産品建立過程進行解耦,可以使用相同的建立過程來得到不同的産品。也就說細節依賴抽象。
-
易于精确控制對象的建立
将複雜産品的建立步驟分解在不同的方法中,使得建立過程更加清晰
-
易于拓展
增加新的具體建造者無需修改原有類庫的代碼,易于拓展,符合“開閉原則“。
每一個具體建造者都相對獨立,而與其他的具體建造者無關,是以可以很友善地替換具體建造者或增加新的具體建造者,使用者使用不同的具體建造者即可得到不同的産品對象。
缺點
- 建造者模式所建立的産品一般具有較多的共同點,其組成部分相似;如果産品之間的差異性很大,則不适合使用建造者模式,是以其使用範圍受到一定的限制。
- 如果産品的内部變化複雜,可能會導緻需要定義很多具體建造者類來實作這種變化,導緻系統變得很龐大。
應用場景
- 需要生成的産品對象有複雜的内部結構,這些産品對象具備共性;
- 隔離複雜對象的建立和使用,并使得相同的建立過程可以建立不同的産品。
示例
Builder模式是怎麼來的
考慮這樣一個場景,假如有一個類(*User*),裡面有很多屬性,并且你希望這些類的屬性都是不可變的(final),就像下面的代碼:
public class User {
private final String firstName; // 必傳參數
private final String lastName; // 必傳參數
private final int age; // 可選參數
private final String phone; // 可選參數
private final String address; // 可選參數
}
在這個類中,有些參數是必要的,而有些參數是非必要的。就好比在注冊使用者時,使用者的姓和名是必填的,而年齡、手機号和家庭位址等是非必需的。那麼問題就來了,如何建立這個類的對象呢?
一種可行的方案就是實用構造方法。第一個構造方法隻包含兩個必需的參數,第二個構造方法中,增加一個可選參數,第三個構造方法中再增加一個可選參數,依次類推,直到構造方法中包含了所有的參數。
public User(String firstName, String lastName) {
this(firstName, lastName, );
}
public User(String firstName, String lastName, int age) {
this(firstName, lastName, age, "");
}
public User(String firstName, String lastName, int age, String phone) {
this(firstName, lastName, age, phone, "");
}
public User(String firstName, String lastName, int age, String phone, String address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phone = phone;
this.address = address;
}
這樣做的好處隻有一個:可以成功運作。但是弊端很明顯:
- 參數較少的時候問題還不大,一旦參數多了,代碼可讀性就很差,并且難以維護。
- 對調用者來說也很麻煩。如果我隻想多傳一個address參數,還必需給age、phone設定預設值。而且調用者還會有這樣的困惑:我怎麼知道第四個String類型的參數該傳address還是phone?
第二種解決辦法就出現了,我們同樣可以根據JavaBean的習慣,設定一個空參數的構造方法,然後為每一個屬性設定setters和getters方法。就像下面一樣:
public class User {
private String firstName; // 必傳參數
private String lastName; // 必傳參數
private int age; // 可選參數
private String phone; // 可選參數
private String address; // 可選參數
public User() {
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
}
這種方法看起來可讀性不錯,而且易于維護。作為調用者,建立一個空的對象,然後隻需傳入我感興趣的參數。那麼缺點呢?也有兩點:
- 對象會産生不一緻的狀态。當你想要傳入5個參數的時候,你必需将所有的setXX方法調用完成之後才行。然而一部分的調用者看到了這個對象後,以為這個對象已經建立完畢,就直接食用了,其實User對象并沒有建立完成。
- *User*類是可變的了,不可變類所有好處都不複存在。
終于輪到主角上場的時候了,利用Builder模式,我們可以解決上面的問題,代碼如下:
public class User {
private final String firstName; // 必傳參數
private final String lastName; // 必傳參數
private final int age; // 可選參數
private final String phone; // 可選參數
private final String address; // 可選參數
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
public static class UserBuilder {
private final String firstName;
private final String lastName;
private int age;
private String phone;
private String address;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
有幾個重要的地方需要強調一下:
- *User*類的構造方法是私有的。也就是說調用者不能直接建立User對象。
- *User*類的屬性都是不可變的。所有的屬性都添加了final修飾符,并且在構造方法中設定了值。并且,對外隻提供getters方法。
- Builder模式使用了鍊式調用。可讀性更佳。
- Builder的内部類構造方法中隻接收必傳的參數,并且該必傳的參數适用了final修飾符。
相比于前面兩種方法,Builder模式擁有其所有的優點,而沒有上述方法中的缺點。用戶端的代碼更容易寫,并且更重要的是,可讀性非常好。唯一可能存在的問題就是會産生多餘的Builder對象,消耗記憶體。然而大多數情況下我們的Builder内部類使用的是靜态修飾的(static),是以這個問題也沒多大關系。
現在,讓我們看看如何建立一個User對象呢?
new User.UserBuilder("金", "坷垃")
.age()
.phone("3838438")
.address("奧格瑞瑪")
.build();
關于Builder的一點說明
線程安全問題
由于Builder是非線程安全的,是以如果要在Builder内部類中檢查一個參數的合法性,必需要在對象建立完成之後再檢查。
正确的寫法:
public User build() {
User user = new user(this);
if (user.getAge() > ) {
throw new IllegalStateException(“Age out of range”); // 線程安全
}
return user;
}
下面的代碼是非線程安全的:
public User build() {
if (age > ) {
throw new IllegalStateException(“Age out of range”); // 非線程安全
}
return new User(this);
}
Android源碼中的建造者模式
在Android源碼中,我們最常用到的Builder模式就是AlertDialog.Builder, 使用該Builder來建構複雜的AlertDialog對象。簡單示例如下 :
//顯示基本的AlertDialog
private void showDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.icon);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("Button1",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("點選了對話框上的Button1");
}
});
builder.setNeutralButton("Button2",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("點選了對話框上的Button2");
}
});
builder.setNegativeButton("Button3",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("點選了對話框上的Button3");
}
});
builder.create().show(); // 建構AlertDialog, 并且顯示
}
那麼它的内部是如何實作的呢,讓我們看一下部分源碼:
// AlertDialog
public class AlertDialog extends Dialog implements DialogInterface {
// Controller, 接受Builder成員變量P中的各個參數
private AlertController mAlert;
// 構造函數
protected AlertDialog(Context context, int theme) {
this(context, theme, true);
}
// 4 : 構造AlertDialog
AlertDialog(Context context, int theme, boolean createContextWrapper) {
super(context, resolveDialogTheme(context, theme), createContextWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
mAlert = new AlertController(getContext(), this, getWindow());
}
// 實際上調用的是mAlert的setTitle方法
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
// 實際上調用的是mAlert的setCustomTitle方法
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
// AlertDialog其他的代碼省略
// ************ Builder為AlertDialog的内部類 *******************
public static class Builder {
// 1 : 存儲AlertDialog的各個參數, 例如title, message, icon等.
private final AlertController.AlertParams P;
// 屬性省略
/**
* Constructor using a context for this builder and the {@link AlertDialog} it creates.
*/
public Builder(Context context) {
this(context, resolveDialogTheme(context, ));
}
public Builder(Context context, int theme) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, theme)));
mTheme = theme;
}
// Builder的其他代碼省略 ......
// 2 : 設定各種參數
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setIcon(int iconId) {
P.mIconId = iconId;
return this;
}
public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return this;
}
public Builder setView(View view) {
P.mView = view;
P.mViewSpacingSpecified = false;
return this;
}
// 3 : 建構AlertDialog, 傳遞參數
public AlertDialog create() {
// 調用new AlertDialog構造對象, 并且将參數傳遞個體AlertDialog
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
// 5 : 将P中的參數應用的dialog中的mAlert對象中
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
}
}
可以看到,通過Builder來設定AlertDialog中的title, message, button等參數, 這些參數都存儲在類型為AlertController.AlertParams的成員變量P中,AlertController.AlertParams中包含了與之對應的成員變量。在調用Builder類的create函數時才建立AlertDialog, 并且将Builder成員變量P中儲存的參數應用到AlertDialog的mAlert對象中,即P.apply(dialog.mAlert)代碼段。我們看看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 >= ) {
dialog.setIcon(mIconId);
}
if (mIconAttrId > ) {
dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
}
}
if (mMessage != null) {
dialog.setMessage(mMessage);
}
if (mPositiveButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
mPositiveButtonListener, null);
}
if (mNegativeButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
mNegativeButtonListener, null);
}
if (mNeutralButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
mNeutralButtonListener, null);
}
if (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// 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);
}
}
}
實際上就是把P中的參數挨個的設定到AlertController中, 也就是AlertDialog中的mAlert對象。從AlertDialog的各個setter方法中我們也可以看到,實際上也都是調用了mAlert對應的setter方法。在這裡,Builder同時扮演了上文中提到的builder、ConcreteBuilder、Director的角色,簡化了Builder模式的設計。
總結
其核心思想是将一個“複雜對象的建構算法”與它的“部件及組裝方式”分離,使得構件算法群組裝方式可以獨立應對變化;複用同樣的建構算法可以建立不同的表示,不同的建構過程可以複用相同的部件組裝方式。
Builder模式目的将一個複雜對象的建構與它的表示分離,使得同樣的建構過程可以建立不同的表示。