第二条 一个类如果有多个参数,考虑用Builder构造者模式
1.
@Data public class Student { //体检用 private String name; private int age; private int height; private int sex; //录取用 private String schoolName; private String profession; private int gradeNo; //分班用 private String idCard; private String stuNo; private String labName; private String dormitoryAddress; private Student(Builder builder) { this.name = builder.name; this.age = builder.age; this.height = builder.height; this.sex = builder.sex; this.schoolName = builder.schoolName; this.profession = builder.profession; this.gradeNo = builder.gradeNo; this.idCard = builder.idCard; this.stuNo = builder.stuNo; this.labName = builder.labName; this.dormitoryAddress = builder.dormitoryAddress; } public static class Builder{ //体检用 公用的用final private final String name; private final int age; private final int height; private final int sex; //录取用 private String schoolName; private String profession; private int gradeNo; //分班用 private String idCard; private String stuNo; private String labName; private String dormitoryAddress; public Builder(String name, int age, int height, int sex) { this.name = name; this.age = age; this.height = height; this.sex = sex ; } public Builder schoolName(String schoolName) { this.schoolName = schoolName; return this; } public Builder profession(String profession) { this.profession = profession; return this; } public Builder gradeNo(int gradeNo) { this.gradeNo = gradeNo; return this; } public Builder idCard (String idCard) { this.idCard = idCard; return this; } public Builder stuNo(String stuNo) { this.stuNo = stuNo; return this; } public Builder labName(String labName) { this.labName = labName; return this; } public Builder dormitoryAddress(String dormitoryAddress) { this.dormitoryAddress = dormitoryAddress; return this; } public Student build() { return new Student(this); } } //测试 public static void main(String[] args) { //各取所需,公用的字段写成Builder的构造方法中! Student zhangsan = new Student.Builder("zhangsan", 28, 168, 0).build(); //体检的张三只要四个基本参数 Student zhangsan1 = new Builder("zhangsan", 28, 168, 0).schoolName("安徽大学").profession("国贸").build(); // 录取学生信息管理系统要的字段 Student zhangsan2 = new Student.Builder("zhangsan", 28, 168, 0).schoolName("安徽大学").profession("国贸").stuNo("学号04012057") .gradeNo(302).dormitoryAddress("寝室号502").build(); System.out.println("张三的体检信息:" + zhangsan); System.out.println("张三被录取后信息:" + zhangsan1); System.out.println("张三分班后:" + zhangsan2); } }
2. 结果
张三的体检信息:Student(name=zhangsan, age=28, height=168, sex=0, schoolName=null, profession=null, gradeNo=0, idCard=null, stuNo=null, labName=null, dormitoryAddress=null) 张三被录取后信息:Student(name=zhangsan, age=28, height=168, sex=0, schoolName=安徽大学, profession=国贸, gradeNo=0, idCard=null, stuNo=null, labName=null, dormitoryAddress=null) 张三分班后:Student(name=zhangsan, age=28, height=168, sex=0, schoolName=安徽大学, profession=国贸, gradeNo=302, idCard=null, stuNo=学号04012057, labName=null, dormitoryAddress=寝室号502)