生成者模式 Build
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
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); } } }
|
- 应用场景
- 优点
- 避免过多setter方法,并且隐藏内部细节
- 链式调用,简洁易懂。
- 缺点
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 yanglau0527@gmail.com