前言
如果你還對builder模式一無所知,還不知道如何去使用的話,我想我這篇文章能夠帶你對這個模式有一個基礎的認識.本文僅針對建造者模式的初學者分享.高手可以自行繞道.相信大家一定在平常編寫代碼的時候,遇到過builder模式,因爲這個模式用起來非常簡潔.幾乎可以一句代碼搞定需要設置的參數, 得到一個實例.大大的方便了使用者編寫代碼的速度.相信用過比較流行的網絡框架,圖片加載框架的童鞋,一定用過.好了,下面我和大家一起分享我學習的經驗.
學習這個模式的目的:
學習之前,還是搞懂爲什麼要學這個模式?這個模式的作用是什麼?
下面我舉一個非常簡單的例子,比如我需要創建一個Person對象,這個person對象中,我有很多個參數,比如:
private int id;
private String name;
private int age;
private String birthday;
private String gender;
private double height;
private double weight;
如果我要一次性設置這麼多的屬性給person,你會不會發現是不是每一次都需要
p1.setName(xxx);
p1.setAge(xxx);
~~~
目前可能就只有這麼幾個參數還好,如果參數多起來了呢?是不是感覺寫的很煩?
因爲我們學習builder可以爲我們減少一些代碼量.增加開發速度.
當然builder模式的作用不僅僅是在此,它還可以結合單利模式進行使用,對同一個對象的多個屬性進行賦值.
但作爲初學者學習,建議還是先把基礎的知識學好,然後自己可以繼續深入研究混合模式開發哦!
下面我們來正式開始學習吧!
進入正題(學習builder模式):
我先給大家寫一個完成建造者模式之後的寫法,好讓大家有個對比
Person person = new Person.PersonBuilder(1231)
.setName("張三")
.setAge(12)
.setBirthday("1998-01-04")
.setHeight(175)
.setGender("man")
.setWeight(60)
.build();
大家其實可以觀察一下,爲什麼可以連續去設置多個屬性呢?是因爲每次返回的都是同一個對象,那麼底層做了什麼邏輯呢?下面我貼出我的代碼:
public class Person {
private int id;
private String name;
private int age;
private String birthday;
private String gender;
private double height;
private double weight;
private Person(PersonBuilder builder) {
this.id = builder.id;
this.name = builder.name;
this.age = builder.age;
this.birthday = builder.birthday;
this.gender = builder.gender;
this.height = builder.height;
this.weight = builder.weight;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public int getAge() {
return age;
}
public String getBirthday() {
return birthday;
}
public String getGender() {
return gender;
}
public double getHeight() {
return height;
}
public double getWeight() {
return weight;
}
public static class PersonBuilder {
private final int id;
private String name;
private int age;
private String birthday;
private String gender;
private double height;
private double weight;
public PersonBuilder(int id) {
this.id = id;
}
public PersonBuilder setName(String name) {
this.name = name;
return this;
}
public PersonBuilder setAge(int age) {
this.age = age;
return this;
}
public PersonBuilder setBirthday(String birthday) {
this.birthday = birthday;
return this;
}
public PersonBuilder setGender(String gender) {
this.gender = gender;
return this;
}
public PersonBuilder setHeight(double height) {
this.height = height;
return this;
}
public PersonBuilder setWeight(double weight) {
this.weight = weight;
return this;
}
public Person build() {
return new Person(this);
}
}
}
下面我給大家講解一下,爲什麼要這麼寫?
首先我們肯定是要把需要創建那個對象空參構造方法給私有的!以便提供給PersonBuilder類使用.我們所有設置屬性的操作都是操作PersonBuilder,而不是直接操作Person,所以呢?我們需要在PersonBuilder類中創建與Person類中相同字段,操作了PersonBuilder類的屬性,間接的操作了Person類的屬性.而要同時達到返回的是同一個對象的話,在每個設置屬性的方法返回的肯定是同一個對象,那麼我們所有的屬性都設置好了,就可以了麼?
肯定不行的,因爲你現在還沒有和Person類進行關聯,所有還無法達到我們想要的效果.就好比,你建房子,你把材料都準備好了,沒有修建也是不行的.因此,我們需要在build方法中創建一個Person實現連接.
public Person build() {
return new Person(this);
}
這樣我們的簡單的builder就已經構造完成了.希望大家能夠從我的文章獲得收穫.
最後感謝大家閱讀本篇文章.!謝謝!