gpt4 book ai didi

具有非平凡子类树的 Java 构建器模式

转载 作者:行者123 更新时间:2023-11-30 10:14:34 26 4
gpt4 key购买 nike

我熟悉将构建器模式与泛型和子类化结合使用,但我看不出如何使它与非平凡的子类树一起工作(即 C extends B extends A)。这是我正在尝试做的一个简单示例:

class A {
private final int value;

protected A(ABuilder builder) {
this.value = builder.value;
}

public int getValue() { return value; }

public static class ABuilder<T extends ABuilder<T>> {
private int value;

public T withValue(int value) {
this.value = value;
return (T) this;
}

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

class B extends A {
private final String name;

public static BBuilder builder() {
return new BBuilder();
}

protected B(BBuilder builder) {
super(builder);
this.name = builder.name;
}

public String getName() { return name; }

public static class BBuilder<U extends BBuilder<U>> extends ABuilder<BBuilder<U>> {
private String name;

public U withName(String name) {
this.name = name;
return (U) this;
}

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

如果我声明没有通用类型的 BBuilder,一切都很好:

public static class BBuilder extends ABuilder<BBuilder>

因为我希望 BBuilder 由 CBuilder 扩展,所以我尝试使用与 ABuilder 相同的 Curiously Recurring Template Pattern。但是像这样,编译器将 BBuilder.withValue() 视为返回 ABuilder,而不是我想要的 BBuilder。这:

    B b = builder.withValue(1)
.withName("X")
.build();

不编译。任何人都可以看到我在这里做错了什么,我一直在尝试不同的泛型模式,但无法让它发挥作用。

感谢任何有建议的人。

最佳答案

看来你的错误只是声明了正确的参数:

class A {

private final int value;

public static <T extends Builder<T>> T builderA() {
return (T)new Builder<>();
}

protected A(Builder<? extends Builder<?>> builder) {
value = builder.value;
}

public static class Builder<T extends Builder<T>> {

private int value;

public T withValue(int value) {
this.value = value;
return (T)this;
}

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

class B extends A {

private final String name;

public static <T extends Builder<T>> T builderB() {
return (T)new Builder<>();
}

protected B(Builder<? extends Builder<?>> builder) {
super(builder);
name = builder.name;
}

public static class Builder<T extends Builder<T>> extends A.Builder<T> {

private String name;

public Builder<T> withName(String name) {
this.name = name;
return this;
}

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

客户端代码:

A a = A.builder().withValue(1).build();
B b = B.builder().withValue(2).withName("xx").build();

关于具有非平凡子类树的 Java 构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50838999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com