第十三章 好菜每回味不同 --- 建造者模式

  1. <?php
  2. //画小人
  3. abstract class PersonBuilder
  4. {
  5. abstract public function BuildHead();
  6. abstract public function BuildBody();
  7. abstract public function BuildArmLeft();
  8. abstract public function BuildArmRight();
  9. abstract public function BuildLegLeft();
  10. abstract public function BuildLegRight();
  11. }
  12. class PersonThinBuilder extends PersonBuilder
  13. {
  14. public function BuildHead()
  15. {
  16. echo "小头\n";
  17. }
  18. public function BuildBody()
  19. {
  20. echo "小身子\n";
  21. }
  22. public function BuildArmRight()
  23. {
  24. echo "右臂\n";
  25. }
  26. public function BuildArmLeft()
  27. {
  28. echo "左臂\n";
  29. }
  30. public function BuildLegLeft()
  31. {
  32. echo "左腿\n";
  33. }
  34. public function BuildLegRight()
  35. {
  36. echo "右腿\n";
  37. }
  38. }
  39. class PersonFatBuilder extends PersonBuilder
  40. {
  41. public function BuildHead()
  42. {
  43. echo "大头\n";
  44. }
  45. public function BuildBody()
  46. {
  47. echo "大身子\n";
  48. }
  49. public function BuildArmRight()
  50. {
  51. echo "右臂\n";
  52. }
  53. public function BuildArmLeft()
  54. {
  55. echo "左臂\n";
  56. }
  57. public function BuildLegLeft()
  58. {
  59. echo "左腿\n";
  60. }
  61. public function BuildLegRight()
  62. {
  63. echo "右腿\n";
  64. }
  65. }
  66. class PersonDirector
  67. {
  68. private $personBuilder;
  69. function __construct($personBuilder)
  70. {
  71. $this->personBuilder = $personBuilder;
  72. }
  73. public function CreatePerson()
  74. {
  75. $this->personBuilder->BuildHead();
  76. $this->personBuilder->BuildBody();
  77. $this->personBuilder->BuildArmRight();
  78. $this->personBuilder->BuildArmLeft();
  79. $this->personBuilder->BuildLegLeft();
  80. $this->personBuilder->BuildLegRight();
  81. }
  82. }
  83. //客户端代码
  84. echo "苗条的:\n";
  85. $thinDirector = new PersonDirector(new PersonThinBuilder());
  86. $thinDirector->CreatePerson();
  87. echo "\n胖的:\n";
  88. $fatDirector = new PersonDirector(new PersonFatBuilder());
  89. $fatDirector->CreatePerson();

总结:

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

如果我们用了建造者模式,那么用户只需要指定需要建造的类型就可以得到他们,而具体建造的过程和细节就不需要知道了。

主要用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常是稳定的,但对象内部的构建通畅面临着复杂的变化。

建造者模式是在当创建复杂对象的算法应该独立于改对象的组成部分以及它们的装配方式时适用的模式。