[英]Is there a way to use the builder pattern in an abstract class?
假设我试图用矩形和椭圆形表示形状,并希望最终添加更多形状。 所以我写了一个抽象类AShape。 在这个抽象类中,我还想抽象字段设置器,例如颜色,宽度,高度和位置。
我的第一个想法是执行生成器模式,但是我知道必须实例化该类才能使用生成器,并且您不能实例化抽象类。 这意味着我必须在具体的类中执行此操作,但这就是重复的代码。 有没有我可以使用的其他模式,还是有办法解决这个问题?
当然,您可以并且正如您所说的那样,使代码的可读性更高,重复次数更少:
public abstract class AShape {
private final String color;
private final int width;
private final int height;
private final int position;
public AShape(String color, int width, int height, int position) {
this.color = color;
this.width = width;
this.height = height;
this.position = position;
}
public String getColor() {
return this.color;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public int getPosition() {
return this.position;
}
}
public class Rectangle extends AShape {
private final int l1;
private final int l2;
public Rectangle(String color, int width, int height, int position, int l1, int l2) {
**super(color, width, height, position);**
this.l1 = l1;
this.l2 = l2;
}
public int getL1() {
return this.l1;
}
public int getL2() {
return this.l2;
}
}
如您所见,您可以在子类中使用构造函数,尽管您将永远无法实例化AShape,因为它是抽象的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.