5

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

这是一个示例代码,说明了我的实现

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

2 回答 2

6

您可能需要考虑使用嵌套MySophisticatedObject.Builder的 extendsMyPrimitiveObject.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.
  }
}
于 2012-04-10T16:18:50.237 回答
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()
  }     
}
于 2012-04-10T16:21:19.160 回答