我有一个类结构,看起来像这样:
class Parent {
public Parent(int property) { /* use property */}
}
class Son extends Parent {
public Son(int parentProperty, String sonProperty) {
super(parentProperty);
/* use son property */
}
}
我想为这两个类创建构建器,这样:
class ParentBuilder {
protected int parentProperty;
public ParentBuilder parentProperty(int parentPropertyValue) {
parentPropertyValue = parentPropertyValue;
return this;
}
public Parent build() {
return new Parent(parentProperty);
}
}
class SonBuilder extends ParentBuilder {
private String sonProperty;
public SonBuilder sonProperty(String sonProperty) {
this.sonProperty = sonProperty;
return this;
}
@Override
public Son build() {
return new Son(parentProperty, sonProperty);
}
}
但这会导致以下问题:
SonBuilder sonBuilder = new SonBuilder();
sonBuilder.sonProperty("aString").build(); // this works and creates Son
sonBuilder.sonProperty("aString").parentProperty(1).build(); // this works and creates Parent instead of Son
sonBuilder.parentProperty(1).sonProperty("aString").build(); // this doesn't work
我意识到我在吹毛求疵,这可以通过不返回 this
(即没有方法链接)来解决,但我想知道是否有一个优雅的解决方案。
编辑
“优雅”这个词似乎有点困惑。
我所说的“优雅”是指允许方法链接且不涉及转换的解决方案。
最佳答案
第一点
sonBuilder.sonProperty("aString").parentProperty(1).build();
this works and creates Parent instead of Son
预计 parentProperty()
会返回一个 ParentBuilder
:
public ParentBuilder parentProperty(int parentPropertyValue) {...
ParentBuilder.build()
创建一个 Parent
:
public Parent build() {
return new Parent(parentProperty);
}
第二点
sonBuilder.parentProperty(1).sonProperty("aString").build(); // this doesn't work
如第一点所述,parentProperty()
返回一个 ParentBuilder
。
ParentBuilder
当然没有 sonProperty()
方法。
所以编译不了。
I'm wondering if there is an elegant solution.
一个优雅的解决方案不是让 SonBuilder
继承 ParentBuilder
而是与 ParentBuilder
字段组合。
例如:
class SonBuilder {
private String sonProperty;
private ParentBuilder parentBuilder = new ParentBuilder();
public SonBuilder sonProperty(String sonProperty) {
this.sonProperty = sonProperty;
return this;
}
public SonBuilder parentProperty(int parentPropertyValue) {
parentBuilder.parentProperty(parentPropertyValue);
return this;
}
public Son build() {
return new Son(parentBuilder.parentProperty, sonProperty);
}
}
您可以这样创建Son
:
SonBuilder sonBuilder = new SonBuilder();
Son son = sonBuilder.sonProperty("aString").parentProperty(1).build();
关于java - 在方法覆盖中返回继承的类而不是父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197777/