我想实现一种设计模式,在其中设置一个基础构建器类(BaseBuilder.java),其他几个构建器类对此扩展。
基本构建器类是抽象的,它包含其他构建器共有的值。每个构建器共享一些共同的元素,也具有独特的元素。
BaseBuilder类示例-
public class BaseBuilder {
private final String key;
private final String token;
public BaseBuilder(Builder<?> builder) {
this.key = builder.key;
this.token = builder.token;
}
@Override
public String toString() {
return "Builder {" +
", key='" + key + '\'' +
", token='" + token + '\'' +
'}';
}
public abstract static class Builder<T extends Builder <T>> {
private String key;
private String token;
public Builder setKey(String key) {
this.key = key;
return this;
}
public Builder setToken(String token) {
this.token = token;
return this;
}
public BaseBuilder build() {
return new BaseBuilder(this);
}
}
}
现在,我想将此BaseBuilder扩展为其他构建器,例如RedCar。
public class RedCar extends BaseBuilder {
private final String redWheelCaps;
public RedCar(RedCardBuilder builder) {
super(builder);
this.redWheelCaps = builder.redWheelCaps;
}
@Override
public String toString() {
return "Red Car Builder {" +
", redWheelCaps='" + redWheelCaps + '\'' +
'}';
}
public static class RedCardBuilder extends BaseBuilder<RedCardBuilder> {
private String redWheelCaps;
public RedCardBuilder setRedWheelCaps(String redWheelCaps) {
this.redWheelCaps = redWheelCaps;
return this;
}
public RedCar build() {
return new RedCar(this);
}
}
}
尝试使用此生成器时,我在尝试获得以下结果时遇到问题。
// this is ideally what I want to achieve
// there is an error because I am not creating a BaseBuilder object
RedCar redCar = new RedCar.RedCarBuilder()
.setKey("key")
.setToken("token")
.setRedWheelCaps("redCaps")
.build();
以上操作无效。系统提示我必须使用BaseBuilder。因此,我将代码更新为以下内容:
// this works good, but the order of my set values causes an error
BaseBuilder redCar = new RedCar.RedCarBuilder()
.setKey("key")
.setToken("token")
.setRedWheelCaps("redCaps")
.build();
我被迫使用多态。很好,但是,在重新排列设置值之前,我仍然有错误。由于某些原因,我必须先设置RedCar的值,然后才能设置BaseBuilder的值。否则,我会收到错误“无法解析方法”。因此,我重新设置了设置值以消除所有错误。
// no errors at all. This works fine but is not what I was expecting
BaseBuilder redCar = new RedCar.RedCarBuilder()
.setRedWheelCaps("redCaps")
.setKey("key")
.setToken("token")
.build();
如何修复设置,以便可以继承和设置值而不必遵循特定顺序?无论如何,无需使用多态性就能完成我想做的事情吗?我有正确的模式构想吗?谢谢!
编辑: 更多信息是,我可以实现我所追求的目标,因此我可以忽略BaseBuilder中的设置器。因此,以下是可以的。
RedCar redCar = new RedCar.RedCarBuilder()
.setRedWheelCaps("redCaps")
.build();
为什么无法从BaseBuilder继承设置器?