BuilderSubclassSubclass

BuilderSubclassSubclass

我正在尝试实现具有多级继承的构建器对象。我从Subclassing a Java Builder class中得到了一些启发,这是我的(简化)代码:

public class StackOverflow {
    public static class Builder<T extends Builder<T>> {
        public Builder() {}

        public T doA() {
            System.out.println("A");
            return (T) this;
        }
    }

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

        public BuilderSubclass() {}

        public T doB() {
            System.out.println("B");
            return (T) this;
        }
    }

    public static class BuilderSubclassSubclass
            extends BuilderSubclass<BuilderSubclassSubclass> {

        public BuilderSubclassSubclass() {}

        public BuilderSubclassSubclass doC() {
            System.out.println("C");
            return this;
        }
    }
}


我想做这样的事情:
new StackOverflow.BuilderSubclassSubclass().doA().doC().doB()

但是,当我调用new StackOverflow.BuilderSubclassSubclass().doA()时,返回的对象不是BuilderSubclassSubclass而是BuilderSubclass<BuilderSubclassSubclass>。我知道为什么会这样:Builder的通用类型是BuilderSubclass<BuilderSubclassSubclass>,它是在BuilderSubclass的类签名中分配的。

关于如何避免此问题的任何想法?

更新:我想我可以避免使用构建器模式,而是调用如下函数:

StackOverflow.BuilderSubclassSubclass builder = new StackOverflow.BuilderSubclassSubclass();
builder.doA();
builder.doB();
builder.doC();


在这种情况下,代码变为:

public class StackOverflowBatchHelperFunctions {
    public static class Builder {

        public Builder() {
        }

        public void doA() {
            System.out.println("A");
        }
    }

    public static class BuilderSubclass extends Builder {
        public BuilderSubclass() {
            super();
        }

        public void doB() {
            System.out.println("B");
        }
    }

    public static class BuilderSubclassSubclass extends BuilderSubclass {
        public BuilderSubclassSubclass() {
            super();
        }

        public void doC() {
            System.out.println("C");
        }
    }
}


但是,我认为这不太“漂亮”,因此我仍然希望看到最初问题的答案。

最佳答案

您应将public static class BuilderSubclass<T extends BuilderSubclass<T>> extends Builder<BuilderSubclass<T>>替换为public static class BuilderSubclass<T extends BuilderSubclass<T>> extends Builder<T>

09-11 20:31