Table of contents
scenes to be used
When the constructor of a class requires four or more parameters, and some parameters can be null, consider using the builder mode.
accomplish
If there is a pdf configuration class that has fields such as size, title, author, color, etc., where the author and color can be omitted, but the size and title must be passed in, and the size has an enumeration value, then The following implementations are possible.
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);
}
}
}
Here's how it's used, which is "much more elegant" than constantly using objects for set or passing in fixed parameters using the constructor
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());
}
}
In some middleware and java api, the builder pattern is relatively common, such as lombok's @Builder
and StringBuilder class
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。