Effective java第2条
1726 ワード
複数のコンストラクタパラメータに遭遇した場合は、コンストラクタを使用することを考慮します.
package Builder;
public class Student {
private final String name;
private final int id;
private final String sex;
private final String birth;
private final String home;
public static class Builder{
private String name;
private int id;
private String sex;
private String birth;
private String home;
public Builder setName(String name){
this.name = name;
return this;
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setSex(String sex) {
this.sex = sex;
return this;
}
public Builder setBirth(String birth) {
this.birth = birth;
return this;
}
public Builder setHome(String home) {
this.home = home;
return this;
}
public Student builder(){
return new Student(this);
}
}
private Student(Builder builder){
this.name = builder.name;
this.sex = builder.sex;
this.id = builder.id;
this.birth = builder.birth;
this.home = builder.home;
}
public String toString(){
return this.name + "'s sex is " + this.sex + "," + this.id + "," + this.home;
}
public static void main(String[] args){
Student s = new Student.Builder().setName("zoe").setSex("Female").setId(1016).setHome("No").builder();
System.out.println(s);
}
}