Build模式/建造者模式
Build模式,在開發中非常常見,也很實用,最常見的,就是創建Dialog的時候,用起來,有點像鏈式調用,看一下我用build模式寫的一個Data對象的調用方法。
創建一個Data對象
Data data = new Data.Builder()
.category(getCategory())
.owner(getOwner())
.content(getContent())
.keys(getKeys())
.uuid(uuid)
.build();
這樣就可以了,省去了繁瑣的set方法,也不用在Data對象中寫入繁瑣的不同的有參構造函數來創建對象,有了build類,我們可以隨意傳入參數個數,調用build方法建造出一個對象。
靜態內部類的Build對象,避免了內部類對外部類引用從而導致內存泄漏,靜態內部類的生命週期,和普通類一樣,new出來創建,系統回收,注意處理好靜態內部類的靜態成員變量引用,建議靜態內部類中不要寫靜態的成員變量。
public class Data {
private String uuid,owner,category,content;
private Keys keys;
public Data() {
}
private Data(Builder builder) {
this.uuid = builder.uuid;
this.owner = builder.owner;
this.category = builder.category;
this.content = builder.content;
this.keys = builder.keys;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Keys getKeys() {
return keys;
}
public void setKeys(Keys keys) {
this.keys = keys;
}
public static class Builder {
private String uuid,owner,category,content;
private Keys keys;
public Builder uuid(String uuid){
this.uuid = uuid;
return this;
}
public Builder owner(String owner){
this.owner = owner;
return this;
}
public Builder category(String category){
this.category = category;
return this;
}
public Builder content(String content){
this.content = content;
return this;
}
public Builder keys(Keys keys){
this.keys = keys;
return this;
}
public Data build() {
return new Data(this);
}
}
}