Effective Java (2) 遇到多個構造器參數時要考慮用構建器

來源:互聯網
上載者:User

一、背景

對於有多個選擇性參數的類,我們一般通過什麼辦法傳遞參數呢?這裡提供了三種辦法:

①. 重疊構造器模式

②. JavaBeans模式

③. Builder構建器模式

下面我們來分析一下以上三種方法的優勢及弊端。

二、重疊構造器模式

重疊構造器模式中第一個構造器中只有必要參數,第二個構造器有一個選擇性參數,第三個構造器中有兩個選擇性參數,依次類推,最後一個構造器中包含所有選擇性參數。這種方案可行,但是有較大缺陷。

缺點:當有很多選擇性參數的時候,用戶端代碼很難編寫,並難以閱讀,如果用戶端不小心顛倒了其中兩個參數的順序,編譯器也不會報錯,但是程式在運行時會出現錯誤的行為。

/*  * 構造器模式  */public class NutritionFacts1 {      private int a1; // 必須      private int a2; // 必須      private int a3; // 可選      private int a4; // 可選            public NutritionFacts1(int a1, int a2) {          this(a1, a2, 0);      }            public NutritionFacts1(int a1, int a2, int a3) {          this(a1, a2, 0, 0);      }            public NutritionFacts1(int a1, int a2, int a3, int a4) {          this.a1 = a1;          this.a2 = a2;          this.a3 = a3;          this.a4 = a4;      }            public int getA1() {          return a1;      }            public void setA1(int a1) {          this.a1 = a1;      }            public int getA2() {          return a2;      }            public void setA2(int a2) {          this.a2 = a2;      }            public int getA3() {          return a3;      }            public void setA3(int a3) {          this.a3 = a3;      }            public int getA4() {          return a4;      }            public void setA4(int a4) {          this.a4 = a4;      }                public String toString() {          return a1 + "-" + a2 + "-" + a3 + "-" + a4;      }            public static void main(String[] args) {          NutritionFacts1 nf = new NutritionFacts1(1, 2, 3, 4);          System.out.println(nf);      }  }

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.