我目前正在使用Builder模式,紧跟维基百科文章中提出的Java实现 Builder模式 http://en.wikipedia.org/wiki/Builder_pattern
这是一个示例代码,用于说明我的实现
public class MyPrimitiveObject {
private String identifier="unknown";
public static class Builder {
private final MyPrimitiveObject obj = new MyPrimitiveObject();
public MyPrimitiveObject build() { return obj; }
public Builder setidentifier (String val) {
obj.identifier = val;
return this;
}
}
public static Builder createBuilder() { return new Builder(); }
@Override public String toString() { return "ID: "+identifier; }
}
在我使用这个类的一些应用程序中,我碰巧找到了非常相似的构建代码,所以我想在MyPrimitiveObject
中继承MySophisticatedObject
并将所有重复的代码移动到它的构造函数中。这是问题所在。
我如何调用超类构建器并将其返回的对象指定为我的实例?
public class MySophisticatedObject extends MyPrimitiveObject {
private String description;
public MySophisticatedObject (String someDescription) {
// this should be the returned object from build() !!
Builder().setidentifier(generateUUID()).build()
description = someDescription;
}
}
答案 0 :(得分:6)
您可能需要考虑使用扩展MySophisticatedObject.Builder
的嵌套MyPrimitiveObject.Builder
,并覆盖其build()
方法。在构建器中有一个受保护的构造函数,以接受要设置值的实例:
public class MyPrimitiveObject {
private String identifier="unknown";
public static class Builder {
private final MyPrimitiveObject obj;
public MyPrimitiveObject build() { return obj; }
public Builder setidentifier (String val) {
obj.identifier = val;
return this;
}
public Builder() {
this(new MyPrimitiveObject());
}
public Builder(MyPrimitiveObject obj) {
this.obj = obj;
}
}
...
}
public class MySophisticatedObject extends MyPrimitiveObject {
private String description;
public static class Builder extends MyPrimitiveObject.Builder {
private final MySophisticatedObject obj;
public Builder() {
this(new MySophisticatedObject());
super.setIdentifier(generateUUID());
}
public Builder(MySophisticatedObject obj) {
super(obj);
this.obj = obj;
}
public MySophisticatedObject build() {
return obj;
}
// Add code to set the description etc.
}
}
答案 1 :(得分:1)
你需要:
public class MySophisticatedObject extends MyPrimitiveObject {
private String description;
public static class SofisitcatedBuilder extends Builder {
private final MySophisticatedObject obj = new MySophisticatedObject();
public MyPrimitiveObject build() { return obj; }
public Builder setDescription(String val) {
obj.description = val;
return this;
}
}
public MySophisticatedObject (String someDescription) {
// this should be the returned object from build() !!
return new SofisitcatedBuilderBuilder()
.setDescription(someDescription)
.setidentifier(generateUUID()).build()
}
}