Telescoping Constructor pattern
当一个类属性较多,需要创建接受许多参数列表的构造方法时,需要这种设计方法。
次等的写法(重复代码较多):
public class Person {
private final String name;
private final String lastName;
private final int age;
private final String profession;
private final List<String> hobbies;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
this.age = 0;
this.profession = null;
this.hobbies = new ArrayList<>();
}
public Person(String name, String lastName, int age) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.profession = null;
this.hobbies = new ArrayList<>();
}
public Person(String name, String lastName, int age, String profession) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.profession = profession;
this.hobbies = new ArrayList<>();
}
public Person(String name, String lastName, int age, String profession, List<String> hobbies) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.profession = profession;
this.hobbies = hobbies == null ? new ArrayList<>() : new ArrayList<>(hobbies);
}
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getProfession() {
return profession;
}
public List<String> getHobbies() {
return Collections.unmodifiableList(hobbies);
}
}
优秀写法(无重复代码):
public class Person {
private final String name;
private final String lastName;
private final int age;
private final String profession;
private final List<String> hobbies;
public Person(String name, String lastName) {
this(name, lastName, 0);
}
public Person(String name, String lastName, int age) {
this(name, lastName, age, null);
}
public Person(String name, String lastName, int age, String profession) {
this(name, lastName, age, profession, null);
}
public Person(String name, String lastName, int age, String profession, List<String> hobbies) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.profession = profession;
this.hobbies = hobbies == null ? new ArrayList<>() : new ArrayList<>(hobbies);
}
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getProfession() {
return profession;
}
public List<String> getHobbies() {
return Collections.unmodifiableList(hobbies);
}
}