1. 程式人生 > >Builder Pattern

Builder Pattern

cto exce 嚴重 屬性設置 不一致 methods 缺點 分表 對象

遇到多個構造器形參時要考慮用構建器

引言

遇到多個構造器時要考慮用構建器(builder重疊構造器(telescoping constructor)
  1. // Telescoping constructor pattern - does not scale well! - Pages 11-12
  2. /**
  3. * 營養成分表
  4. */
  5. public class NutritionFacts {
  6. private final int servingSize; // (mL) required
  7. private final int servings; // (per container) required
  8. private final int calories; // optional
  9. private final int fat; // (g) optional
  10. private final int sodium; // (mg) optional
  11. private final int carbohydrate; // (g) optional
  12. /**
  13. * 重疊構造器模式:提供第一個只有必要參數的構造器
  14. */
  15. public
    NutritionFacts(int servingSize, int servings) {
  16. this(servingSize, servings, 0);
  17. }
  18. /**
  19. * 重疊構造器模式:第二個構造器有一個可選參數
  20. */
  21. public NutritionFacts(int servingSize, int servings, int calories) {
  22. this(servingSize, servings, calories, 0);
  23. }
  24. /**
  25. * 重疊構造器模式:第三個構造器在第二個構造器的基礎上,加一個可選參數
  26. */
  27. public NutritionFacts(int servingSize, int servings, int calories, int fat) {
  28. this(servingSize, servings, calories, fat, 0);
  29. }
  30. /**
  31. * 重疊構造器模式:以此類推
  32. */
  33. public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) {
  34. this(servingSize, servings, calories, fat, sodium, 0);
  35. }
  36. /**
  37. * 重疊構造器模式:以此類推
  38. */
  39. public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) {
  40. this.servingSize = servingSize;
  41. this.servings = servings;
  42. this.calories = calories;
  43. this.fat = fat;
  44. this.sodium = sodium;
  45. this.carbohydrate = carbohydrate;
  46. }
  47. public static void main(String[] args) {
  48. NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27);
  49. }
  50. }
缺點:① 當有許多參數的時候,客戶端代碼會很難編寫,並且仍然較難以閱讀。② 如果讀者想知道那些值是什麽意思,必須很仔細地數著這些參數來探個究竟。如果客戶端不小心顛倒了其中兩個參數的順序,編譯器也不會出錯,但是在程序運行時會出現錯誤行為。
JavaBeans模式
  1. // JavaBeans Pattern - allows inconsistency, mandates mutability - Pages 12-13
  2. public class NutritionFacts {
  3. // Parameters initialized to default values (if any)
  4. private int servingSize = -1; // Required; no default value
  5. private int servings = -1; // " " " "
  6. private int calories = 0;
  7. private int fat = 0;
  8. private int sodium = 0;
  9. private int carbohydrate = 0;
  10. public NutritionFacts() { }
  11. // Setters
  12. public void setServingSize(int val) {
  13. servingSize = val;
  14. }
  15. public void setServings(int val) {
  16. servings = val;
  17. }
  18. public void setCalories(int val) {
  19. calories = val;
  20. }
  21. public void setFat(int val) {
  22. fat = val;
  23. }
  24. public void setSodium(int val) {
  25. sodium = val;
  26. }
  27. public void setCarbohydrate(int val) {
  28. carbohydrate = val;
  29. }
  30. public static void main(String[] args) {
  31. // 調用一個無參構造器來創建對象,然後調用setter()方法來設置
  32. NutritionFacts cocaCola = new NutritionFacts();
  33. cocaCola.setServingSize(240);
  34. cocaCola.setServings(8);
  35. cocaCola.setCalories(100);
  36. cocaCola.setSodium(35);
  37. cocaCola.setCarbohydrate(27);
  38. }
  39. }
缺點:① 無法保證一致性:JavaBean模式自身有著很嚴重的缺點,因為構造過程被分到了幾個調用中,在構造過程中JavaBean可能處在不一致的狀態。試圖使用處於不一致狀態的對象,將會導致失敗,這種失敗調試起來十分困難② 阻止了把類做成不可變

Builder模式

  1. // Builder Pattern - Pages 14-15
  2. public class NutritionFacts {
  3. private final int servingSize;
  4. private final int servings;
  5. private final int calories;
  6. private final int fat;
  7. private final int sodium;
  8. private final int carbohydrate;
  9. /**
  10. * 註意是static修飾, 作為NutritionFacts的靜態成員類
  11. * 詳細的討論請參考:
  12. * https://stackoverflow.com/questions/5007355/builder-pattern-in-effective-java
  13. */
  14. public static class Builder {
  15. // Required parameters
  16. private final int servingSize;
  17. private final int servings;
  18. // Optional parameters - initialized to default values
  19. private int calories = 0;
  20. private int fat = 0;
  21. private int carbohydrate = 0;
  22. private int sodium = 0;
  23. public Builder(int servingSize, int servings) {
  24. System.out.println("NutritionFacts.Builder init this[" + this + "]");
  25. this.servingSize = servingSize;
  26. this.servings = servings;
  27. }
  28. // builder的setter()方法返回builder本身,以便可以把調用鏈接起來
  29. public Builder calories(int val) {
  30. calories = val;
  31. return this;
  32. }
  33. public Builder fat(int val) {
  34. fat = val;
  35. return this;
  36. }
  37. public Builder carbohydrate(int val) {
  38. carbohydrate = val;
  39. return this;
  40. }
  41. public Builder sodium(int val) {
  42. sodium = val;
  43. return this;
  44. }
  45. /**
  46. * build()方法可以檢驗這些約束條件
  47. * 如果違反了任何約束條件build方法就應該拋出IllegalSelectorException
  48. */
  49. public NutritionFacts build() {
  50. return new NutritionFacts(this);
  51. }
  52. }
  53. /**
  54. * 註意這是private修飾的
  55. */
  56. private NutritionFacts(Builder builder) {
  57. servingSize = builder.servingSize;
  58. servings = builder.servings;
  59. calories = builder.calories;
  60. fat = builder.fat;
  61. sodium = builder.sodium;
  62. carbohydrate = builder.carbohydrate;
  63. }
  64. public static void main(String[] args) {
  65. // 不直接生成想要的對象,而是讓客戶端利用所有必要的參數調用NutritionFacts.Builder(int, int)創建一個builder對象
  66. // 然後客戶端在builder對象調用類似於setter的方法,來設置每個相關的可選參數
  67. // 最後客戶端調用無參的build()方法來生成不可變的對象NutritionFacts
  68. NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();
  69. NutritionFacts cocaCola2 = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).fat(7).build();
  70. }
  71. }
優點:
① Builder方式創建的對象,在調用 build() 方法之前是不會創建NutritionFacts 對象的,所有的屬性設置都必須在 build() 方法之前,而且創建了NutritionFacts 對象後就不可以更改其屬性了,這就保證了對象狀態的唯一性,而且代碼的可讀性也提高了。② 如果有些參數是必填的,可以加到 Builder 的構造函數中缺點:Builder模式的確也有自身不足,為了創建對象,必須先創建它的構建器,在某些十分註重性能的情況下,可能就成為問題了。

參考

  • Builder Pattern in Effective Java
  • Too Many Parameters in Java Methods, Part 3: Builder Pattern

Builder Pattern