我要做的是创建一个使用 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 不能声明为静态的;静态类型只能在静态或顶级类型中声明。
或者,我可以将内部类创建MyCube
为常规类,但问题是我无法引用DrawMyCube
类内部的任何内容(在实际用例中,有很多对这些内容的引用)。