关于构造者模式,可以参考https://www.jianshu.com/p/f36dbec7adb4
示例
public class Student {
private String ID;
private String name;
private int age;
private String sex;
public Student(Builder builder) {
this.ID = builder.ID;
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
}
public Student(String ID, String name, int age, String sex) {
this.ID = ID;
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"ID='" + ID + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public static class Builder{
private String ID;
private String name;
private int age;
private String sex;
public Builder ID(String ID) {
this.ID = ID;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder sex(String sex) {
this.sex = sex;
return this;
}
public Student build() {
return new Student(this);
}
}
}
调用
public class BuilderDemo {
public static void main(String[] args) {
Student student = new Student.Builder().age(18).sex("男").build();
Student student1 = new Student.Builder().age(10).ID("12314").name("wang").sex("女").build();
System.out.println(student);
System.out.println(student1);
}
}