建造者模式
借鉴于
参考地址
这里Director被省略
Builder为建筑后的产品Product
Inner为具体的建筑者ConcreteBuilder
Inner如果生成方法接口则为建造者Builder
//建筑者模式可以使用lombok @Data注解实现
public class Builder {
private String name;
private Integer age;
//使用Inner对象接收参数
public static Inner builder() {
return new Inner();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
//inner可以被替换为一个与Builder同成员变量类 即Inner替换为外部类其他不变
private static class Inner{
private String name;
private Integer age;
public Inner name(String name) {
this.name=name;
return this;
}
public Inner age(Integer age) {
this.age=age;
return this;
}
//build返回参数
public Builder build() {
Builder builder = new Builder();
builder.setName(this.name);
builder.setAge(this.age);
return builder;
}
}
@Override
public String toString() {
return "Builder{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
Builder a = Builder.builder().name("a").age(123).build();;
System.out.println(a);
}
}