我想做的是创建一个使用Builder模式的类(Square),然后将该类扩展为需要使用的对象(MyCube)中的内部类(DrawMyCube)。

由于有些复杂的原因,最好将它们扩展为内部类(对局部变量的引用)。

我试图使该示例尽可能简单,因为实际用例太复杂而无法在此处使用:

public abstract class Square {
    protected Integer length;
    protected Integer width;

    public abstract static class Builder {
        protected Integer length;
        protected Integer width;

        public abstract Builder length(Integer length);
        public abstract Builder width(Integer width);
    }

    protected Square(Builder builder) {
        this.length = builder.length;
        this.width = builder.width;
    }
}


现在我需要在这里扩展和使用它:

public class DrawMyCube {
    private String myText;
    private Integer height;
    private String canvas;
    private MyCube myCube;

    public DrawMyCube(String canvas) {
        this.canvas = canvas;
        myCube = new MyCube.Builder().length(10).width(10).text("HolaWorld").build();
    }

    public void drawRoutine() {
        myCube.drawMe(canvas);
    }

    protected class MyCube extends Square {
        protected String text;

        public static class Builder extends Square.Builder{
            protected String text;

            public Square.Builder length(Integer length) {this.length = length; return this;}
            public Square.Builder width(Integer width) {this.width = width; return this;}
            public Square.Builder text(String text) {this.text = text; return this;}
        }

        protected MyCube(Builder builder) {
            super(builder);
            this.text = text;
        }

        protected void drawMe(String canvas) {
            canvas.equals(this);
        }
    }
}


但是问题是内部类中的静态Builder:


成员类型Builder不能声明为静态;静态类型可以
仅在静态或顶级类型中声明。


或者,我可以将内部类MyCube创建为常规类,但问题是我无法引用回DrawMyCube类内部的任何内容(在实际用例中,有很多引用涉及到这些内部引用)。

最佳答案

静态嵌套类只能在静态上下文中声明,这就是为什么您看到该编译器错误的原因。只需将您的Builder类声明为与MyCube相邻(或在静态上下文中的任何其他位置,都没有关系)。例如:

public class DrawMyCube {

    protected class MyCube extends Square { }

    public static class MyCubeBuilder extends Square.Builder { }
}


请注意,构建器将需要引用外部DrawMyCube实例以实例化新的MyCube。因此,您可以将其设为MyCube的内部(非静态)类:

public class DrawMyCube {

    protected class MyCube extends Square { }

    public class MyCubeBuilder extends Square.Builder { }
}


如您所见,我仍然在MyCube旁边声明它,因为将构建器作为其构建内容的内部类根本没有意义。

编辑:正如您提到的,一个简单的替代方法是使MyCube静态:

public class DrawMyCube {

    protected static class MyCube extends Square {

        public static class Builder extends Square.Builder { }
    }
}


因为说实话,使用内部类并没有什么好处-仅使用隐式外部实例引用-这将使您保留现有的层次结构和命名约定。您可以轻松地自己实现对外部DrawMyCube的引用-只需多一点代码即可。



附带说明一下,您可能要使用泛型来实现构建器模式,例如,抽象的Builder<T>,其中实现会构建T的实例。实际上,将没有办法缩小派生的生成器类产生的结果。这是我要提示的草图:

abstract class Square { }

abstract class SquareBuilder<T extends Square> { }

class MyCube extends Square { }

class MyCubeBuilder extends SquareBuilder<MyCube> { }

09-08 08:36