So, in the famous Effective Java book, it introduces a Builder pattern where you can have an inner static Builder class to instantiate a class. The book suggests the following design of a class:
public class Example {
private int a;
private int b;
public static class Builder() {
private int a;
private int b;
public Builder a(int a) {
this.a = a;
return this;
}
public Builder b(int b) {
this.b = b;
return this;
}
public Example build() {
return new Example(this);
}
}
private Example(Builder builder) {
this.a = builder.a;
this.b = builder.b;
}
}
However I have failed to understand why do we really need an inner Builder class? The above code have duplicate lines for field declarations (int a, b), this would become relatively messy if we had more fields.
Why not just get rid of the Builder class, and let Example class take on all the set methods that were in Builder class?
So to instantiate Example, it would become Example e = new Example().a(3).b.(3); instead of Example e = new Example.Builder.a(3).b(3).build();
NOTE: The book suggests this pattern for classes that have a long list of parameters to be set.
Aucun commentaire:
Enregistrer un commentaire