1.当一个类有很多参数,其中一些是必须的,一些是可选的时候,使用构建器清晰明了:
下面的类可以修改为构造器
/**
* Created by kaizige on 2017/7/3.
*/
public class Person {
private int age;//必须
private String name;//必须
private String sex;//必须
private String father;
private String mother;
public Person(int age, String name, String sex, String father, String mother) {
this.age = age;
this.name = name;
this.sex = sex;
this.father = father;
this.mother = mother;
}
public Person(int age, String name, String sex,String father){
this(age,name,sex,father,null);
}
public Person(int age, String name, String sex){
this(age,name,sex,null,null);
}
}
/**
* Created by kaizige on 2017/7/3.
*/
public class Person2 {
private int age;//必须
private String name;//必须
private String sex;//必须
private String father;
private String mother;
@Override
public String toString() {
return "Person2{" +
"age=" + age +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", father='" + father + '\'' +
", mother='" + mother + '\'' +
'}';
}
public Person2(Builder builder){
this.age=builder.age;
this.name=builder.name;
this.father=builder.father;
this.mother=builder.mother;
this.sex=builder.sex;
}
public static class Builder{
private int age;//必须
private String name;//必须
private String sex;//必须
private String father=null;
private String mother=null;
public Builder(int age, String name, String sex){
this.age = age;
this.name = name;
this.sex = sex;
}
public Builder withFather(String father){
this.father=father;
return this;
}
public Builder withMother(String mother){
this.mother=mother;
return this;
}
public Person2 build(){
return new Person2(this);
}
}
public static void main(String[] args) {
System.out.println(new Builder(22,"杨凯","男").withFather("杨").withMother("王").build());
}
}