Builder Pattern Java:如何在 Base Builder 中为泛型基类引用泛型类型

Builder Pattern Java: How to reference generic type in BaseBuilder for Generic BaseClass

我想为 Generic Base class 实现 Builder 模式,而 Sub class 卡在 Base Builder 中定义 Generic 类型。这是 classes.

子 Class:

public class Sub extends Base<T> {
 private final String key;
      private Sub(Builder builder) {
       super(builder);
       this.key = builder.key;
     }
public static SubBuilder extends Base.BaseBuilder<SubBuilder> {
     String key;
    public SubBuilder key(String key) {
      this.key = key;
      return this;
    }
  @Override
  public Sub build() {
  return new Sub(this);
  }
}
}

基础 Class :


public class Base<T> {
 private final T type;
 protected Base(BaseBuilder<?> build) {
  this.type = build.type; 
}
//Base Builder
public static class BaseBuilder<B extends BaseBuilder<B>> {
 T type;  //This is obviously not right because T is not static reference 
 public B type(T type) {
 this.type = type;
  return (B)this;
}
public Base build() {
return new Base(this);
}
} 
}

如前所述,无法在 BaseBuilder 中引用 T 类型。如何在此处使用构建器设置 T。 也无法从 BaseBuilder 中删除静态。 建造者模式适用于这类问题吗?

T 类型参数添加到 BaseBuilderSubSubBuilder:

public class Base<T> {
    private final T type;

    protected Base(BaseBuilder<?, T> build) {
        this.type = build.type;
    }

    public static class BaseBuilder<B extends BaseBuilder<B, T>, T> {
        private T type;

        public B type(T type) {
            this.type = type;
            return (B) this;
        }

        public Base<T> build() {
            return new Base<>(this);
        }
    }
}
public class Sub<T> extends Base<T> {
    private final String key;

    private Sub(SubBuilder<T> builder) {
        super(builder);
        this.key = builder.key;
    }

    public static class SubBuilder<T> extends BaseBuilder<SubBuilder<T>, T> {
        private String key;

        public SubBuilder<T> key(String key) {
            this.key = key;
            return this;
        }

        @Override
        public Sub<T> build() {
            return new Sub<>(this);
        }
    }
}