Which of the following is the best approach to implement the builder pattern?
1) Using an object for assembly instead of all its properties in the builder (and create it in the constructor constructor):
public class Person { private String firstName;
2) Using the properties of the object for assembly instead of the object directly in the builder (and create it in the build () method):
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; } } }
I prefer the first method, because I think that with many properties, repeating them in the builder is redundant. Are there some flaws with the first approach?
Thanks in advance and sorry for my bad english.
source share