首页 > 代码库 > Builder Pattern

Builder Pattern

遇到多个构造器形参时要考虑用构建器

引言

遇到多个构造器时要考虑用构建器(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