在子类中使用Builder模式从构造(use Builder pattern from the co

2019-06-23 12:16发布

我目前使用Builder模式,密切关注Java实现在维基百科的文章Builder模式建议http://en.wikipedia.org/wiki/Builder_pattern

这是我的ilustrates实施示例代码

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; }
}

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

我如何可以调用父类Builder和转让其返回的对象为我的实例?

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;
  }     
}

Answer 1:

您可能要考虑有一个嵌套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.
  }
}


Answer 2:

你需要:

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()
  }     
}


文章来源: use Builder pattern from the constructor in a subclass
标签: java builder