第一章 代码无错就是优 ---简单工厂模式

1.简单工厂模式

  1. <?php
  2. /**
  3. * Operation
  4. */
  5. class Operation
  6. {
  7. protected $a = 0;
  8. protected $b = 0;
  9. public function setA($a)
  10. {
  11. $this->a = $a;
  12. }
  13. public function setB($b)
  14. {
  15. $this->b = $b;
  16. }
  17. public function getResult()
  18. {
  19. $result = 0;
  20. return $result;
  21. }
  22. }
  23. /**
  24. * Add
  25. */
  26. class OperationAdd extends Operation
  27. {
  28. public function getResult()
  29. {
  30. return $this->a + $this->b;
  31. }
  32. }
  33. /**
  34. * Mul
  35. */
  36. class OperationMul extends Operation
  37. {
  38. public function getResult()
  39. {
  40. return $this->a * $this->b;
  41. }
  42. }
  43. /**
  44. * Sub
  45. */
  46. class OperationSub extends Operation
  47. {
  48. public function getResult()
  49. {
  50. return $this->a - $this->b;
  51. }
  52. }
  53. /**
  54. * Div
  55. */
  56. class OperationDiv extends Operation
  57. {
  58. public function getResult()
  59. {
  60. return $this->a / $this->b;
  61. }
  62. }
  63. /**
  64. * Operation Factory
  65. */
  66. class OperationFactory
  67. {
  68. public static function createOperation($operation)
  69. {
  70. switch ($operation) {
  71. case '+':
  72. $oper = new OperationAdd();
  73. break;
  74. case '-':
  75. $oper = new OperationSub();
  76. break;
  77. case '/':
  78. $oper = new OperationDiv();
  79. break;
  80. case '*':
  81. $oper = new OperationMul();
  82. break;
  83. }
  84. return $oper;
  85. }
  86. }
  87. // 客户端代码
  88. $operation = OperationFactory::createOperation('+');
  89. $operation->setA(1);
  90. $operation->setB(2);
  91. echo $operation->getResult() . PHP_EOL;

总结

学会通过分封装,继承,多态把程序的藕合度降低

复用,不是复制!

高内聚,低耦合