当前位置:   article > 正文

设计模式-创建型模式-建造者模式

设计模式-创建型模式-建造者模式

建造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一种对象创建型模式。

建造者模式一步一步地创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。

 

  1. // 'Product' 类
  2. public class Product {
  3. private String partA;
  4. private String partB;
  5. private String partC;
  6. public void setPartA(String partA) {
  7. this.partA = partA;
  8. }
  9. public void setPartB(String partB) {
  10. this.partB = partB;
  11. }
  12. public void setPartC(String partC) {
  13. this.partC = partC;
  14. }
  15. public void showProduct() {
  16. System.out.println("Part A: " + partA);
  17. System.out.println("Part B: " + partB);
  18. System.out.println("Part C: " + partC);
  19. }
  20. }
  21. // 'Builder' 抽象接口
  22. public interface Builder {
  23. void buildPartA();
  24. void buildPartB();
  25. void buildPartC();
  26. Product getProduct();
  27. }
  28. // 'ConcreteBuilder1' 类
  29. public class ConcreteBuilder1 implements Builder {
  30. private Product product = new Product();
  31. @Override
  32. public void buildPartA() {
  33. product.setPartA("This is part A.");
  34. }
  35. @Override
  36. public void buildPartB() {
  37. product.setPartB("This is part B.");
  38. }
  39. @Override
  40. public void buildPartC() {
  41. product.setPartC("This is part C.");
  42. }
  43. @Override
  44. public Product getProduct() {
  45. return product;
  46. }
  47. }
  48. // 'ConcreteBuilder2' 类
  49. public class ConcreteBuilder2 implements Builder {
  50. private Product product = new Product();
  51. @Override
  52. public void buildPartA() {
  53. product.setPartA("This is part A.");
  54. }
  55. @Override
  56. public void buildPartB() {
  57. product.setPartB("This is part B.");
  58. }
  59. @Override
  60. public void buildPartC() {
  61. product.setPartC("This is part C.");
  62. }
  63. @Override
  64. public Product getProduct() {
  65. return product;
  66. }
  67. }
  68. // 'Director' 类
  69. public class Director {
  70. private Builder builder;
  71. public Director(Builder builder) {
  72. this.builder = builder;
  73. }
  74. public void constructProduct() {
  75. builder.buildPartA();
  76. builder.buildPartB();
  77. builder.buildPartC();
  78. Product product = builder.getProduct();
  79. product.showProduct();
  80. }
  81. }
  82. // 客户端代码
  83. public class Client {
  84. public static void main(String[] args) {
  85. Builder builder1 = new ConcreteBuilder1();
  86. Director director1 = new Director(builder1);
  87. director1.constructProduct();
  88. Builder builder2 = new ConcreteBuilder2();
  89. Director director2 = new Director(builder2);
  90. director2.constructProduct();
  91. }
  92. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/162169
推荐阅读
相关标签
  

闽ICP备14008679号