实现构建器模式的 Java 最佳方法
以下哪项是实现生成器模式的更好方法?
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;
}
}
}
我更喜欢第一种方法,因为我认为在构建器中重复它们有很多属性是多余的。第一种方法是否有一些缺点?
提前感谢,抱歉我的英语不好。