假设我有一个抽象类(BaseThing)。它有一个必需参数(“base required”)和一个可选参数(“base optional”)。我有一个扩展它的具体类(事物)。它还具有一个必需参数(“required”)和一个可选参数(“optional”)。所以像:
public abstract class BaseThing {
public static final String DEFAULT_BASE_OPTIONAL = "Default Base Optional";
private final String baseRequired;
private String baseOptional = DEFAULT_BASE_OPTIONAL;
protected BaseThing(final String theBaseRequired) {
this.baseRequired = theBaseRequired;
}
final void setBaseOptional(final String newVal) {
this.baseOptional = newVal;
}
public final void selfDescribe() {
System.out.println("Base Required: " + baseRequired);
System.out.println("Base Optional: " + baseOptional);
selfDescribeHook();
}
protected abstract void selfDescribeHook();
}
和:
public final class Thing extends BaseThing {
public static final String DEFAULT_OPTIONAL = "Default Optional";
private final String required;
private String optional = DEFAULT_OPTIONAL;
Thing(final String theRequired, final String theBaseRequired) {
super(theBaseRequired);
required = theRequired;
}
@Override
protected void selfDescribeHook() {
System.out.println("Required: " + required);
System.out.println("Optional: " + optional);
}
void setOptional(final String newVal) {
optional = newVal;
}
}
我想为 Thing 对象创建一个 Joshua Bloch 风格的构建器。不过,更一般地说,我想让 BaseThing 的具体实现更容易拥有构建器,所以我真正想要的(我认为)是一个 BaseThing 构建器,它可以很容易地用于制作 ThingBuilder、OtherThingBuilder 或 SuperThingBuilder .
有没有比我想出的以下更好的方法(或者我想出的方法有问题)?
public abstract class BaseThingBuilder<T extends BaseThing> {
private String baseOptional = BaseThing.DEFAULT_BASE_OPTIONAL;
public BaseThingBuilder<T> setBaseOptional(final String value) {
baseOptional = value;
return this;
}
public T build() {
T t = buildHook();
t.setBaseOptional(baseOptional);
return t;
}
protected abstract T buildHook();
}
和:
public final class ThingBuilder extends BaseThingBuilder<Thing> {
private final String baseRequired;
private final String required;
private String optional = Thing.DEFAULT_OPTIONAL;
public ThingBuilder(final String theRequired,
final String theBaseRequired) {
required = theRequired;
baseRequired = theBaseRequired;
}
public ThingBuilder setOptional(final String value) {
optional = value;
return this;
}
protected Thing buildHook() {
Thing thing = new Thing(required, baseRequired);
thing.setOptional(optional);
return thing;
}
}
可用于以类似于以下方式构建 Thing 对象:
BaseThingBuilder<Thing> builder =
new ThingBuilder("Required!", "Base Required!")
.setOptional("Optional!")
.setBaseOptional("Base Optional!");
Thing thing = builder.build();
thing.selfDescribe();
哪个输出:
Base Required: Base Required!
Base Optional: Base Optional!
Required: Required!
Optional: Optional!
我知道但我认为不是特别重要的一个问题(尽管如果可以改进它会很好)是您必须在设置任何基本选项之前设置所有非基本选项:做否则会导致语法错误,因为 setBaseOptional() 返回的是 BaseThingBuilder 而不是 ThingBuilder。
提前致谢。