前言
在使用一些熱門第三方框架的時候,我們往往會發現,比如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, 0);
}
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(25)
.phone("3838438")
.address("奧格瑞瑪")
.build();
關於Builder的一點說明
線程安全問題
由於Builder是非線程安全的,所以如果要在Builder內部類中檢查一個參數的合法性,必需要在對象創建完成之後再檢查。
正確的寫法:
public User build() {
User user = new user(this);
if (user.getAge() > 120) {
throw new IllegalStateException(“Age out of range”); // 線程安全
}
return user;
}
下面的代碼是非線程安全的:
public User build() {
if (age > 120) {
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, 0));
}
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 >= 0) {
dialog.setIcon(mIconId);
}
if (mIconAttrId > 0) {
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模式目的將一個複雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示。