第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有好的方法繼承一個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() 之前調(diào)用 withX(),則 withY() 方法將無法編譯,因為 withX() 方法沒有返回 PointBuilderWithY 類。PointBuilder 基類沒有 withY() 方法。我知道我可以向基類添加一個抽象的 withY() 方法,但這違背了這一點。我想將 withY() 方法的使用限制為僅那些需要它的對象。換句話說,我希望編譯器強制執(zhí)行使用第一個 PointBuilder 時不能調(diào)用 withY() 的限制。同時,我不想告訴我的用戶必須按特定順序指定選項,因為這會造成混亂。我更喜歡編寫萬無一失的系統(tǒng)。用戶希望以任意順序指定選項,這使得該類更易于使用。有沒有辦法做到這一點?
查看完整描述

1 回答

?
慕姐4208626

TA貢獻1852條經(jīng)驗 獲得超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 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號