待构建的类
import lombok.ToString;
@ToString
public class Student {
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
}
建造者
public class StudentBuilder {
private String name;
private Integer age;
private static volatile StudentBuilder studentBuilder;
// 构造器 私有
private StudentBuilder() {
}
public StudentBuilder name(String name) {
this.name = name;
return studentBuilder;
}
public StudentBuilder age(Integer age) {
this.age = age;
return studentBuilder;
}
public Student build() {
return new Student (this.name, this.age);
}
public static StudentBuilder builder() {
if (studentBuilder == null) {
synchronized (StudentBuilder.class) {
if (studentBuilder == null)
studentBuilder = new StudentBuilder ();
}
}
return studentBuilder;
}
}