当前位置:Gxlcms > PHP教程 > PHP组合模式第一种实现方式

PHP组合模式第一种实现方式

时间:2021-07-01 10:21:17 帮助过:28人阅读

PHP组合模式第一种实现方式

  1. <?php
  2. // 组合模式
  3. function echoLine($msg) {
  4. echo $smg, '<br/>';
  5. }
  6. interface Component
  7. {
  8. public function doAction();
  9. }
  10. /**
  11. * 局部类
  12. */
  13. class Leaf implements Component
  14. {
  15. public function doAction()
  16. {
  17. echoLine('The [leaf] doAction!');
  18. }
  19. }
  20. /**
  21. * 组合模式的一个问题是如何实现 add 和 remove 方法。一般的组合模式会在抽象超类中添加 add
  22. * 和 remove 方法。这可以确保模式中的所有类都共享同一个借口,但这同时也意味着局部类也必须
  23. * 实现这些方法。实际上,我们并不希望在局部类中实现这些方法。
  24. *
  25. * 需要担心的问题:
  26. * 1. 组合操作的成本。
  27. * 2. 对象持久化问题。难以直接将数据保存在关系型数据中,但其数据却非常适合持久化为 XML。
  28. */
  29. class Composite implements Component
  30. {
  31. /**
  32. * component container
  33. */
  34. private $container = array();
  35. public function doAction()
  36. {
  37. echoLine('The [Composite] doAction!');
  38. foreach ($this->container as $c)
  39. $c->doAction();
  40. }
  41. /**
  42. * add component
  43. * @param Component $c
  44. */
  45. public function addComponent(Component $c)
  46. {
  47. if(!in_array($c, $this->container, true))
  48. $this->container[] = $c;
  49. }
  50. /**
  51. * remove conponent
  52. * @param Component $c
  53. */
  54. public function removeComponent(Component $c)
  55. {
  56. $this->container = array_diff($this->container, array($c));
  57. }
  58. /**
  59. * get all components
  60. * @return array
  61. */
  62. public function getComponents()
  63. {
  64. return $this->container;
  65. }
  66. }
  67. // test code
  68. $leaf = new Leaf();
  69. $composite = new Composite();
  70. $composite->addComponent($leaf);
  71. $composite->addComponent(new Leaf());
  72. $composite->addComponent(new Leaf());
  73. $composite->doAction();

以上就是PHP组合模式第一种实现方式的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行