When I create the Builder pattern, I used to always passe a builder object to a class private constructor and initialize static inner class builder properties to the outer class.
public class Outer {
private final String name;
private final String country;
private final String zipcode;
// option 1
private Outer(String name, String country, String zipcode) {
super();
this.name = name;
this.country = country;
this.zipcode = zipcode;
}
// option 2
public Outer(Builder builder) {
this.country = builder.country;
this.name = builder.name;
this.zipcode = builder.zipcode;
}
static class Builder {
private String name;
private String country;
private String zipcode;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setZipsetCountry(String zip) {
this.zipcode = zip;
return this;
}
public Builder setCountry(String country) {
this.country = country;
return this;
}
//option 1
Outer build() {
return new Outer(name, country, zipcode);
}
//option 2
Outer buildOption2() {
return new Outer(this);
}
}
}
In this case, I use to use always option 2. However, one of my college's point of view is then the builder class couple with the Outer class. But I think it is ok to be couple outer class with an inner class as it is the nature of the inner class. That is inner class virtually organizing Outer class further.
With the first option, it could be cumbersome when there is 20, 30 parameters to passe as it always defer the point of having a builder pattern. My college's argument is it happens only once. At this point, I kind of stuck, look like both are OK to me. What am I missing here?
Aucun commentaire:
Enregistrer un commentaire