使用子类中构造函数的Builder模式

PA.*_*PA. 5 java builder

我目前正在使用Builder模式,紧跟维基百科文章Builder模式中 建议的Java实现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; }
}
Run Code Online (Sandbox Code Playgroud)

在一些使用该类我的应用程序,我偶然发现非常相似的建筑规范,所以我想子类MyPrimitiveObjectMySophisticatedObject和移动我的所有重复的代码到它的构造..这里是问题.

我如何调用超类构建器并将其返回的对象分配为我的实例?

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;
  }     
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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.
  }
}
Run Code Online (Sandbox Code Playgroud)