I can\'t decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor
I would implement the builder pattern like this:
package so1632058;
public class MyClass {
private final String param1;
private final String param2;
MyClass(Builder builder) {
this.param1 = builder.param1;
this.param2 = builder.param2;
}
public String getParam1() {
return param1;
}
public String getParam2() {
return param2;
}
@SuppressWarnings("hiding")
public static final class Builder {
String param1;
String param2;
public Builder param1(String param1) {
this.param1 = param1;
return this;
}
public Builder param2(String param2) {
this.param2 = param2;
return this;
}
public MyClass toMyClass() {
return new MyClass(this);
}
}
}
And then have the following code to use it:
package so1632058;
public class Main {
public static void main(String[] args) {
MyClass.Builder builder = new MyClass.Builder();
builder.param1("p1").param2("p2");
MyClass instance = builder.toMyClass();
instance.toString();
}
}
Some notes:
MyClass
constructor.MyClass
is via the Builder
.