Ruby (Rails) 程序员 2 年,刚刚切换到另一个使用 Java 的团队。对 Java builder 模式有一些疑问。
我了解使用这种模式的好处,即避免创建不一致状态的可伸缩构造函数和 java bean 设置器,但我无法准确理解它是如何工作的,以下是团队要求我使用的确切模式:
public class Person
{
//why is it so important that this be final, hence immutable
private final String firstName;
private final String lastName;
// Constructor
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
//I have absolutely no idea what is this for and why is this necessary
public static Builder builder()
{
return new Builder();
}
//This is an inner class, where person is the outer class (the owning class)
//but why is this has to be a static class?
public static class Builder
{
private String firstName;
private String lastName;
public Builder withFirstName(String firstName)
{
//this.firstName refers to the Builder instance firstName
this.firstName = firstName;
return this;
//what is this return this? returning this instance of the Builder object?
}
public Builder withLastName(String lastName)
{
this.lastName = lastName;
return this;
}
public Person build()
{
return new Person(firstName, lastName);
//firstName and lastName here refer to the Builder's object instance vars,
//and used to create a new person object
}
}
}
要使用它:
Person p = new Person.Builder(5).firstName("foo").lastName("bar").build();
1) Builder 的参数“5”是做什么用的?
2)为什么Builder内部类是静态的?
3) public static Builder builder() 方法有什么用?
4)我是否正确,我们实际上是在创建一个新的内部类 - Builder 对象,这个内部类中的 build 方法返回一个新的 Person 对象?
5) 看来要创建这个 Person 类,我必须将内存使用量增加一倍,一个用于外部类,一个用于内部类,这样效率低吗?
6)我是否正确,我仍然可以通过 Person p = new Person("foo", "bar"); 创建一个新的人对象;
7)有人将如何对此进行单元测试?如何对 setter 和 getter 进行单元测试?
8) 我可以对任何字段进行验证吗?
9)我如何指定一个字段是必需的,所以如果有人试图构建一个只有名字但没有提供姓氏的字段,它将引发异常。
提前谢谢了!