【发布时间】:2017-11-09 09:08:25
【问题描述】:
我有一个类似这样的类结构:
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(即没有方法链接)来解决,但我想知道是否有一个优雅的解决方案。
编辑
“优雅”这个词似乎有点混乱。
“优雅”是指允许方法链接且不涉及强制转换的解决方案。
【问题讨论】:
-
我是一个 C++ 人,所以不确定,但你的第三行真的会创建一个
Parent对象吗?还是Son对象并将其作为Parent引用返回? -
@king_nak 是的,我实际上是在询问返回
this时是否可以返回当前类(Parent或Son)。没有强制转换,也没有放弃方法链接。
标签: java inheritance builder fluent overriding