构造者(Builder)模式
public class Student {
private String name;
private int age;
private String sex;
private String phone;
private String email;
public Student(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
this.phone = builder.phone;
this.email = builder.email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
static class Builder {
private String name;
private int age;
private String sex;
private String phone;
private String email;
public Student build() {
return new Student(this);
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setSex(String sex) {
this.sex = sex;
return this;
}
public Builder setPhone(String phone) {
this.phone = phone;
return this;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
}
}
class test {
public static void main(String[] args) {
Student student = new Student.Builder()
.setName("Tom")
.setAge(18)
.setSex("male")
.setPhone("1234567890")
.setEmail("tom@example.com")
.build();
System.out.println(student.getName());
}
}