How does builder pattern works
Ruby (Rails) programmer for 2 years, just switched to another team that
uses Java. Have some questions about Java builder pattern.
I understand the benefits of using this pattern, namely to avoid the
telescoping constructor and the java bean setters which creates an
inconsistent state but I have trouble understanding exactly how it works,
the following is the exact pattern the team requires me to use:
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
}
}
}
To use it:
Person p = new Person.Builder(5).firstName("foo").lastName("bar").build();
1) What is the param "5" to the Builder for?
2) Why is it the Builder inner class be static?
3) What is the use of public static Builder builder() method?
4) Am I correct that we are actually creating a new inner class - Builder
object, which the build method within this inner class return a new Person
object?
5) It seems that to create this Person class, I would have to double the
memory usage, one for the outer class and one for the inner class, is that
in-efficient?
6) Am I correct that I can still create a new person object by Person p =
new Person("foo", "bar");
7) How would someone unit test this? How to unit test the setters and
getters?
8) Can I perform validation on any of the fields?
9) How do I specifiy that a field is required, so it will throw an
exception were someone tries to build one with only a firstName, but no
lastName supplied.
Many thanks in advance!
No comments:
Post a Comment