I am trying to create a class with many parameters using the Builder pattern, rather than telescoping constructors. I do this as described by Joshua Bloch Effective Java, having a private constructor in a wrapper class and an open static class Builder. The Builder class ensures that the object is in a consistent state before calling the build () function, after which it delegates the construction of the object to the private constructor. In this way,
public class Foo {
private Foo(Builder b) {
}
public static final class Builder {
public Builder() {
}
public Builder var1(Var var) {
return this;
}
public Foo build() {
return new Foo(this);
}
}
}
Then I want to add type restrictions to some of the variables, and therefore I need to parameterize the class definition. I want the boundaries of the Foo class to be the same as the Builder class.
public class Foo<Q extends Quantity> {
private final Unit<Q> units;
private Foo(Builder<Q> b) {
}
public static final class Builder<Q extends Quantity> {
private Unit<Q> units;
public Builder() {
}
public Builder units(Unit<Q> units) {
this.units = units;
return this;
}
public Foo build() {
return new Foo<Q>(this);
}
}
}
, , , , . .
public static final Foo.Builder<Acceleration> x_Body_AccelField =
new Foo.Builder<Acceleration>()
.units(SI.METER)
.build();
units Unit<Acceleration>, Unit<Length>, .
? , .