I very interested in the builder pattern, I use it often but I am not sure if the builders I make are good enough and also I have doubts about all the surroundings where I can use them. This is an example of how I create a builder:
public class Person {
private String name;
private String secondName;
private int age;
public static class Builder {
private boolean isBuilt;
private Person person = new Person();
private void check() {
if (isBuilt) {
throw new IllegalStateException(
"The object cannot be modified after built");
}
}
public Builder withName(String name) {
check();
person.name = name;
return this;
}
public Builder withSecondName(String secondName) {
check();
person.secondName = secondName;
return this;
}
public Builder withAge(int age) {
check();
person.age = age;
return this;
}
public Person build() {
check();
isBuilt = true;
return person;
}
}
@Override
public String toString() {
return "Name: " + name + "\nSecond name:" + secondName + "\nAge:" + age;
}
}
Just a quick usage example:
Person person = new Person.Builder()
.withName("John")
.withSecondName("Smith")
.withAge(50)
.build();
System.out.println(person);
Here some of my doubts:
- Do you think it is really immutable?If no, How can I improve it?
- About thread safety. Well this is probably my main doubt. Is this really thread safe? I saw examples on the internet that say that the class level variables must be final and passed via a constructor. Also I saw one example where the variables were declared as volatile. What do you think about it?
- Do you think that this builder would have any limitation in what regards the scenario where it can be used? What I mean is would it be suitable to be called in either an EJB, a JSF backing bean, an MDB,or become a JPA entity...?