我希望使用静态内部类实现构建者模式,例如对于类A(具有字段a1、a2、a3)、类B(具有字段b1、b2)和类C(具有字段c1),它们都从超类SuperClass继承字段s1、s2:
public class A extends SuperClass {
private final String a1;
...
private A(ABuilder builder) {
super(builder);
this.a1 = builder.a1;
...
}
public static class ABuilder extends SuperClassBuilder implements ABuilderInterface {
private String a1;
...
@Override
public ABuilder withA1(String a1) {
this.a1 = a1;
return this;
}
...
@Override
public SuperClass build() {
return new A(this);
}
}
}
针对B和C的情况,建造者只是不同之处在于它们有自己的字段并实现了自己的接口(BBuilderInterface 和 CBuilderInterface),而这些接口仅定义了要实现哪些方法。
public interface ABuilderInterface extends SuperClassBuilderInterface {
ABuilderInterface withA1(String a1);
...
}
...<interfaces for B and C>
public interface SuperClassBuilderInterface {
SuperClassBuilderInterface withS1(String s1);
...
SuperClass build();
}
// Usage of the builders:
public SuperClass foo() {
return new A.ABuilder()
.withA1(...) // returns ABuilderInterface
...
.withS1(...) // returns SuperClassBuilderInterface
...
.build();
}
public abstract class SuperClass {
private final String s1;
...
protected SuperClass(SuperClassBuilder builder) {
this.s1 = builder.s1;
...
}
protected static abstract class SuperClassBuilder implements SuperClassBuilderInterface {
private String s1;
...
@Override
public SuperClassBuilder withS1(String s1) {
this.s1 = s1;
return this;
}
...
@Override
public abstract SuperClass build();
}
}
现在,您可能会发现一个限制,即当我使用构建器时,必须首先调用与子类相关的with...方法,然后链接超类的方法,这不是什么大问题,但仍不确定是否是良好的实践方法。另一方面,我可以将子类的with...方法全部添加到超类接口中,然后限制就消失了,但是我会得到一个包含不同子类的混合with...方法的接口。您更喜欢/建议哪一个?
ABuilder
中的withS1()
返回什么? - alayor