code_junkie

When would you use the Builder Pattern? [closed]

Nov 12th, 2011
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. BuildOrderHeaderRow()
  2. BuildLineItemSubHeaderRow()
  3. BuildOrderRow()
  4. BuildLineItemSubRow()
  5.  
  6. Pizza(int size) { ... }
  7. Pizza(int size, boolean cheese) { ... }
  8. Pizza(int size, boolean cheese, boolean pepperoni) { ... }
  9. Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
  10.  
  11. Pizza pizza = new Pizza(12);
  12. pizza.setCheese(true);
  13. pizza.setPepperoni(true);
  14. pizza.setBacon(true);
  15.  
  16. public class Pizza {
  17. private int size;
  18. private boolean cheese;
  19. private boolean pepperoni;
  20. private boolean bacon;
  21.  
  22. public static class Builder {
  23. //required
  24. private final int size;
  25.  
  26. //optional
  27. private boolean cheese = false;
  28. private boolean pepperoni = false;
  29. private boolean bacon = false;
  30.  
  31. public Builder(int size) {
  32. this.size = size;
  33. }
  34.  
  35. public Builder cheese(boolean value) {
  36. cheese = value;
  37. return this;
  38. }
  39.  
  40. public Builder pepperoni(boolean value) {
  41. pepperoni = value;
  42. return this;
  43. }
  44.  
  45. public Builder bacon(boolean value) {
  46. bacon = value;
  47. return this;
  48. }
  49.  
  50. public Pizza build() {
  51. return new Pizza(this);
  52. }
  53. }
  54.  
  55. private Pizza(Builder builder) {
  56. size = builder.size;
  57. cheese = builder.cheese;
  58. pepperoni = builder.pepperoni;
  59. bacon = builder.bacon;
  60. }
  61. }
  62.  
  63. Pizza pizza = new Pizza.Builder(12).cheese(true).pepperoni(true).bacon(true).build();
  64.  
  65. m.expects(once())
  66. .method("testMethod")
  67. .with(eq(1), eq(2))
  68. .returns("someResponse");
  69.  
  70. Map<String, Integer> m = new HashMap<String, Integer>()
  71. .put("a", 1)
  72. .put("b", 2)
  73. .put("c", 3);
  74.  
  75. class RestaurantObjectBuilder
  76. {
  77. IFactory _factory = new DefaultFoodFactory();
  78.  
  79. //This can be used when you want to plugin the
  80. public void SetFoodFactory(IFactory customFactory)
  81. {
  82. _factory = customFactory;
  83. }
  84.  
  85. public IFactory GetFoodFactory()
  86. {
  87. return _factory;
  88. }
  89. }
  90.  
  91. class RestaurantObjectBuilder
  92. {
  93. IFactory _factory = new DefaultFoodFactory();
  94.  
  95. //This can be used when you want to plugin the
  96. public void SetFoodFactory(IFactory customFactory)
  97. {
  98. _factory = customFactory;
  99. }
  100.  
  101. public IFactory GetFoodFactory()
  102. {
  103. return _factory;
  104. }
  105. }
Add Comment
Please, Sign In to add comment