为了账号安全,请及时绑定邮箱和手机立即绑定

有没有好的方法继承一个Builder类来添加更多选项?

有没有好的方法继承一个Builder类来添加更多选项?

UYOU 2023-09-13 10:13:19
如果我尝试继承一个构建器来添加更多选项,我会收到一个不需要的要求,即选项必须按特定顺序设置。例如,让我为类 java.awt.geom.Point2D 构建两个构建器。在基础构建器中,我们只能设置 X,但在扩展基础构建器的第二个构建器中,我们还可以设置 Y:private static class PointBuilder{  private double x = 0.0;  protected double y = 0.0;  PointBuilder withX(double x) {    this.x = x;    return this;  }  Point2D build() {    return new Point2D.Double(x, y);  }}private static class PointBuilderWithY extends PointBuilder {  PointBuilder withY(double y) {    this.y = y;    return this;  }}public static void main(String[] args) {  Point2D pt1 = new PointBuilder()      .withX(5.0)//      .withY(3.0)  // withY() doesn't compile, which is the intended behavior      .build();  // I can use a PointBuilderWithY only if I set the Y option first.  Point2D pt2 = new PointBuilderWithY()      .withY(3.0)      .withX(5.0)      .build();  // If I set the X option first, the Y option doesn't build!  Point2D pt3 = new PointBuilderWithY()      .withX(5.0)      .withY(3.0) // Won't compile! withX() didn't return a PointBuilderWithY      .build();  System.out.println(pt1);  System.out.println(pt2);  System.out.println(pt3);}如果我在 withY() 之前调用 withX(),则 withY() 方法将无法编译,因为 withX() 方法没有返回 PointBuilderWithY 类。PointBuilder 基类没有 withY() 方法。我知道我可以向基类添加一个抽象的 withY() 方法,但这违背了这一点。我想将 withY() 方法的使用限制为仅那些需要它的对象。换句话说,我希望编译器强制执行使用第一个 PointBuilder 时不能调用 withY() 的限制。同时,我不想告诉我的用户必须按特定顺序指定选项,因为这会造成混乱。我更喜欢编写万无一失的系统。用户希望以任意顺序指定选项,这使得该类更易于使用。有没有办法做到这一点?
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

重写PointBuilderWithY所有PointBuilder方法以返回PointerBuilderWithY实例。


private static class PointBuilderWithY extends PointBuilder {

  @Override

  PointBuilderWithY withX(double x) {

    return (PointBuilderWithY) super.withX(x);

  }


  PointBuilderWithY withY(double y) {

    this.y = y;

    return this;

  }

}


查看完整回答
反对 回复 2023-09-13
  • 1 回答
  • 0 关注
  • 37 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信