定義
separate the construction of a complex object from its representation so that the same construction process can create different representations.
將一個(gè)復(fù)雜對(duì)象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示。
使用場景
- 相同的方法,不同的執(zhí)行順序,產(chǎn)生不同的事件結(jié)果時(shí)槽唾。
- 多個(gè)部件或零件,都可以裝配到一個(gè)對(duì)象中,但是產(chǎn)生的運(yùn)行結(jié)果又不相同時(shí)航背。
- 產(chǎn)品類非常復(fù)雜,或者產(chǎn)品類中的調(diào)用順序不同產(chǎn)生了不同的作用棱貌,這個(gè)使用建造者模式非常適合玖媚。
- 當(dāng)初始化一個(gè)對(duì)象特別復(fù)雜時(shí),如參數(shù)多婚脱,且很多參數(shù)有默認(rèn)值今魔。
Android應(yīng)用場景
- android中的AlertDialog對(duì)話框的構(gòu)建過程。
- Android的各種開源庫障贸,例如Retrofit的創(chuàng)建错森,OkHttp中OkHttpClient和Request。
Java應(yīng)用場景
- 在MyBatis3中通過SqlSessionFactoryBuilder構(gòu)建SqlSessionFactory對(duì)象
Builder模式代碼實(shí)現(xiàn)
public class DoDoContact {
private final int age;
private final int safeID;
private final String name;
private final String address;
public int getAge() {
return age;
}
public int getSafeID() {
return safeID;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public static class Builder {
private int age = 0;
private int safeID = 0;
private String name = null;
private String address = null;
// 構(gòu)建的步驟
public Builder(String name) {
this.name = name;
}
public Builder age(int val) {
age = val;
return this;
}
public Builder safeID(int val) {
safeID = val;
return this;
}
public Builder address(String val) {
address = val;
return this;
}
public DoDoContact build() { // 構(gòu)建篮洁,返回一個(gè)新對(duì)象
return new DoDoContact(this);
}
}
private DoDoContact(Builder b) {
age = b.age;
safeID = b.safeID;
name = b.name;
address = b.address;
}
}
Builder模式總結(jié)
優(yōu)點(diǎn)
- 良好的封裝性涩维, 使用建造者模式可以使客戶端不必知道產(chǎn)品內(nèi)部組成的細(xì)節(jié);
- 建造者獨(dú)立袁波,容易擴(kuò)展瓦阐;
- 在對(duì)象創(chuàng)建過程中會(huì)使用到系統(tǒng)中的一些其它對(duì)象,這些對(duì)象在產(chǎn)品對(duì)象的創(chuàng)建過程中不易得到篷牌;
- 構(gòu)造過程使用了鏈?zhǔn)秸{(diào)用睡蟋,代碼簡潔。
缺點(diǎn)
- 會(huì)產(chǎn)生多余的Builder對(duì)象增加內(nèi)存消耗枷颊;