生成者模式 Build
將一個復雜對象的構(gòu)建與它的表示分離胡陪,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class Build {
public static void main(String[] args) {
Car audi = new Car.Builder()
.color(Color.BLACK)
.money(300000)
.kind("A4")
.year(2020)
.build();
System.out.println(audi.getMoney());
}
}
class Car{
String kind;
Color color;
int year;
int money;
private Car(Builder builder) {
setKind(builder.kind);
setColor(builder.color);
setYear(builder.year);
setMoney(builder.money);
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public static final class Builder {
private String kind;
private Color color;
private int year;
private int money;
public Builder() {
}
public Builder kind(String val) {
kind = val;
return this;
}
public Builder color(Color val) {
color = val;
return this;
}
public Builder year(int val) {
year = val;
return this;
}
public Builder money(int val) {
money = val;
return this;
}
public Car build() {
return new Car(this);
}
}
}
- 應用場景
- Android中,對話框的創(chuàng)建
- OkHttp
- 優(yōu)點
- 避免過多setter方法,并且隱藏內(nèi)部細節(jié)
- 鏈式調(diào)用,簡潔易懂。
- 缺點
- 內(nèi)部類與外部類相互引用龙宏,可能會導致內(nèi)存消耗比較大