流利的生成器与继承的抽象类

问题描述

我正在尝试对类进行较小的分层以使用Builder模式。只有一个abstract类(有点像具有公共字段的基类)。这个有接近15个字段/成员,因此是构建器方法

abstract类的外观如下:

public abstract class AbstractItem {
  private Long id;

  private String type;

  private String status;

  protected AbstractItem () { }

  protected AbstractItem (final BuilderBase<?> builder) {
    id = builder.id;
    type = builder.type;
    status = builder.status;
  }

  public Long getId() { return id; }

  public String getType() { return type; }

  public String getStatus() { return status; }

  protected abstract static class BuilderBase<T extends BuilderBase<T>> {
    private Long id;

    private String type;

    private String status;

    protected abstract T self();

    public T withId(final Long value) {
      id = value;
      return self();
    }

    public T withType(final String value) {
      type = value;
      return self();
    }

    public T withStatus(final String value) {
      status = value;
      return self();
    }

    // PROBLEM 1
    // public abstract T build(); // Nice to have!
  }
}

...这可能是它的扩展类之一:

public final class Item extends AbstractItem {
  private String device;

  public Item() { }

  public Item(final BuilderBase<?> builder) {
    super(builder);
    device = builder.device;
  }

  public static BuilderBase<?> builder() { return new Builder(); }

  public String getDevice() { return device; }

  public static class BuilderBase<T extends BuilderBase<T>> extends AbstractItem.BuilderBase<T> {
    private String device;

    // PROBLEM 2
    @Override
    protected T self() { throw new IllegalStateException("Can't touch this!"); }

    public T withDevice(final String value) {
      device = value;
      return self();
    }

    public Item build() { return new Item(this); }
  }

  protected static class Builder extends BuilderBase<Builder> {
    @Override
    protected Builder self() { return this; }
  }
}

它现在可以正常工作:

return Item.builder()
    .withId(1_100L)
    .withType("ITEM_01")
    .withStatus("CREATED")
    .withDevice("MAGIC_SWORD")
    .build();

但是我这里有两个问题:

  • 是否可以为继承的类正确实现protected T self()? —到目前为止,我只能从其中返回null或引发异常。
  • 是否有一种方法来声明public abstract T build()(在abstract BuilderBase类中),使得从其继承的类必须提供自己的实现?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)