【问题标题】:Is there a way to use the builder pattern in an abstract class?有没有办法在抽象类中使用构建器模式?
【发布时间】:2018-06-07 00:14:08
【问题描述】:

假设我试图表示形状矩形和椭圆形,最终可以灵活地添加更多形状。所以我写了一个抽象类AShape。在这个抽象类中,我还想抽象出颜色、宽度、高度和位置等字段设置器。

我的第一个想法是做构建器模式,但我知道必须实例化类才能使用构建器,而你不能实例化抽象类。这意味着我必须在具体的类中进行,但那是重复的代码。我可以使用另一种模式吗,或者有什么方法可以解决这个问题?

【问题讨论】:

  • 建造者页。通常用于在实例化具有大量属性的类时提高可读性,其中一些属性是可选的。这听起来不像你的情况。
  • 嗯,好的,谢谢。我想我可以在抽象类中做一堆设置器,然后就可以了。
  • 希望将所有字段设为最终字段。将公共字段放在具有受保护构造函数的 AShape 中。如果您使用构建器,则每个具体类都有一个,但将常见的东西移到一个抽象构建器中,所有构建器都是其子类。

标签: java oop design-patterns


【解决方案1】:

当然你可以,正如你所说的,代码的可读性更高,重复更少:

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,因为它是抽象的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2020-07-01
    相关资源
    最近更新 更多