当对象成员变量太多时,使用建造方法给变量赋值往往变得很臃肿,所以可以这样做
public class Something {
private String a;
private String b;
private String c;
private String d;
private String e;
public Something(Builder builder) {
this.a = builder.a;
this.b = builder.b;
this.c = builder.c;
this.d = builder.d;
this.e = builder.e;
}
static class Builder{
private String a;
private String b;
private String c;
private String d;
private String e;
public Builder setA(String a) {
this.a = a;
return this;
}
public Builder setB(String b) {
this.b = b;
return this;
}
public Builder setC(String c) {
this.c = c;
return this;
}
public Builder setD(String d) {
this.d = d;
return this;
}
public Builder setE(String e) {
this.e = e;
return this;
}
public Something build() {
return new Something(this);
}
}
public static void main(String[] args) {
Something something = new Something.Builder().setA("a").setB("b").
setC("c").setD("d").setE("e").build();
System.out.println(something.a);
}
对传统建造者模式的理解
传统建造者模式,可以将实体类中的部分属性抽象出来并单独建造,并且实体的构建过程交予构造者。我认为这是外观模式和策略模式的结合。
关于传统建造者模式可以看如下文章文章来源:https://www.toymoban.com/news/detail-684515.html
秒懂设计模式之建造者模式(Builder pattern) - shusheng007的文章 - 知乎文章来源地址https://www.toymoban.com/news/detail-684515.html
到了这里,关于对建造者模式理解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!