一、Student包含构建器类
创建Student类,包含StudentBuilder构建器,替代Student的构造方法:
package cays.build;
/**
* 学生类
* @create 2020/1/7
**/
public class Student {
private String name;
private String nick;
private String password;
private double score;
private int age;
private String gender;
private Student(StudentBuilder builder) {
this.name = builder.name;
this.nick = builder.nick;
this.password = builder.password;
this.score = builder.score;
this.age = builder.age;
this.gender = builder.gender;
}
public static class StudentBuilder {
private String name;
private String nick;
private String password;
private double score;
private int age;
private String gender;
public StudentBuilder() {
}
public StudentBuilder setName(String name) {
this.name = name;
return this;
}
public StudentBuilder setNick(String nick) {
this.nick = nick;
return this;
}
public StudentBuilder setPassword(String password) {
this.password = password;
return this;
}
public StudentBuilder setScore(double score) {
this.score = score;
return this;
}
public StudentBuilder setAge(int age) {
this.age = age;
return this;
}
public StudentBuilder setGender(String gender) {
this.gender = gender;
return this;
}
public Student build() {
return new Student(this);
}
}
@Override
public String toString() {
return "姓名:" + name + ",昵称:" + nick + ",密码:" + password + ",分数:" + score + ",年龄:" + age + ",性别:" + gender;
}
public String getName() {
return name;
}
public String getNick() {
return nick;
}
public String getPassword() {
return password;
}
public double getScore() {
return score;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
二、测试构建器
测试一下:
package cays.build;
/**
* 测试Java构建器模式
* @create 2020/1/7
**/
public class StudentBuilderMain {
public static void main(String[] args) {
Student student = new Student.StudentBuilder().setName("a")
.setNick("b")
.setPassword("ccc")
.build();
System.out.println(student.toString());
Student student1 = new Student.StudentBuilder().setName("b").setAge(13).build();
System.out.println(student1.toString());
}
}
三、测试结果
测试结果: