以下哪种方法是实现建造者模式的更好方法?
1) 使用对象来构建,而不是在建造者中使用所有属性(并在建造者构造函数中创建它):
public class Person {
private String firstName;
// other properties ...
private Person() {}
// getters ...
public static class Builder {
// person object instead of all the person properties
private Person person;
public Builder() {
person = new Person();
}
public Builder setFirstName(String firstName) {
person.firstName = firstName;
return this;
}
// other setters ...
public Person build() {
if (null == person.firstName) {
throw new IllegalStateException("Invalid data.");
}
return person;
}
}
}
2)在构建器中使用对象的属性来构建对象,而不是直接构建对象(并在build()方法中创建它):
public class Person {
private String firstName;
// other properties ...
private Person() {}
// getters ...
public static class Builder {
// person properties instead of object
private String firstName;
// other properties ...
public Builder() {}
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
// other setters ...
public Person build() {
if (null == this.firstName) {
throw new IllegalStateException("Invalid data.");
}
Person person = new Person();
person.firstName = firstName;
return person;
}
}
}
我更喜欢第一种方式,因为我认为在构建器中重复大量属性是多余的。第一种方法有什么缺点吗?
提前感谢您,对我的糟糕英语表示抱歉。