Recently I searched for a way to initialize a complex object without passing a lot of parameter to the constructor. I tried it with the builder pattern,
public class Complex {
private final String first;
private final String second;
private final String third;
public static class False {}
public static class True {}
public static class Builder {
private String first;
private String second;
private String third;
private Builder() {}
public static Builder create() {
return new Builder<>();
}
public Builder setFirst(String first) {
this.first = first;
return (Builder)this;
}
public Builder setSecond(String second) {
this.second = second;
return (Builder)this;
}
public Builder setThird(String third) {
this.third = third;
return (Builder)this;
}
}
public Complex(Builder builder) {
first = builder.first;
second = builder.second;
third = builder.third;
}
public static void test() {
// Compile Error!
Complex c1 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2"));
// Compile Error!
Complex c2 = new Complex(Complex.Builder.create().setFirst("1").setThird("3"));
// Works!, all params supplied.
Complex c3 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2").setThird("3"));
}
}