目录
- 应用场景
- 实现
应用场景
当一个类的构造函数须要四个及以上的参数,且某些参数可为空,能够思考选用建造者模式。
实现
如果当初有个 pdf 的配置类其中有尺寸、题目、作者、色彩等字段,其中作者和色彩是能够不传入的然而尺寸和题目是必须传入的,并且尺寸是有枚举值的,那么能够进行以下实现。
public class PdfConfig {
public static final String A3 = "A3";
public static final String A4 = "A4";
/**
* 尺寸
*/
private final String specification;
/**
* 题目
*/
private final String title;
/**
* 作者
*/
private final String author;
/**
* 色彩
*/
private String color;
private PdfConfig(Builder builder) {
this.specification = builder.specification;
this.title = builder.title;
this.author = builder.author;
this.color = builder.color;
}
@Override
public String toString() {
return "PdfConfig{" +
"specification='" + specification + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", color='" + color + '\'' +
'}';
}
public static class Builder{
private String specification;
private String title;
private String author;
private String color;
public Builder setSpecification(String sf){
this.specification = sf;
return this;
}
public Builder setTitle(String title){
this.title = title;
return this;
}
public Builder setAuthor(String author){
this.author = author;
return this;
}
public Builder setColor(String color){
this.color = color;
return this;
}
public PdfConfig build(){if (!A3.equals(specification) && !A4.equals(specification)){throw new RuntimeException("尺寸不合规");
}else if (title == null){throw new RuntimeException("请输出题目");
}
return new PdfConfig(this);
}
}
}
上面是其应用过程,这样就相比一直地应用对象进行 set 或者应用构造函数传入固定参数而言,” 优雅得多 ”
public class PdfConfigDemo {public static void main(String[] args) {PdfConfig pdfConfig = new PdfConfig.Builder()
.setSpecification(PdfConfig.A3)
.setAuthor("eacape")
.setTitle("hello")
.build();
System.out.printf(pdfConfig.toString());
}
}
在一些中间件和 java api 中,建造者模式还是比拟常见的,例如 lombok 的 @Builder
和 StringBuilder 类