1. 管道模式也叫流水线模式,对于管道模式来说,有三个对象,管道,载荷,过滤器(阀门)<br />再管道种对附载进行一系列的处理,因为可以对过滤器进行动态添加,所以对负载的处理可以变得更加灵活<br />但同时过滤器过多,很淡把握整体的处理逻辑,而且再某一个过滤器对载荷处理后,因为载荷改变,会造成下一个过滤器种的逻辑出现问题<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22438777/1636365022018-d4c5294b-31dc-49cf-ab5b-9b897649b741.png#clientId=u9cf3090d-49a4-4&from=paste&height=442&id=u79f22593&margin=%5Bobject%20Object%5D&name=image.png&originHeight=442&originWidth=801&originalType=binary&ratio=1&size=23687&status=done&style=none&taskId=u5194cad4-27bf-4ec7-a7fe-75fe40a6ec0&width=801)
    1. <?php
    2. /**
    3. * 管道抽象类
    4. */
    5. interface PipelineInterface
    6. {
    7. //数据载荷
    8. public function __construct($payLoad);
    9. //添加过滤器
    10. public function pipe(StageInterface $stage);
    11. //执行
    12. public function process();
    13. }
    14. /**
    15. * 过滤器抽象类
    16. */
    17. interface StageInterface
    18. {
    19. //处理逻辑
    20. public function handle($payLoad);
    21. }
    22. /**
    23. * 过滤器A
    24. */
    25. class StageA implements StageInterface
    26. {
    27. public function handle($payLoad)
    28. {
    29. echo "StageAddHundred<pre>";
    30. return $payLoad + 100;
    31. }
    32. }
    33. class StageB implements StageInterface
    34. {
    35. public function handle($payLoad)
    36. {
    37. echo "StageMultiHundred<pre>";
    38. return $payLoad * 100;
    39. }
    40. }
    41. /**
    42. * 管道实现类
    43. */
    44. class Pipeline implements PipelineInterface
    45. {
    46. private $pipes;
    47. private $payLoad;
    48. public function __construct($payLoad)
    49. {
    50. $this->payLoad = $payLoad;
    51. }
    52. public function pipe(StageInterface $stage)
    53. {
    54. $this->pipes[] = $stage;
    55. return $this;
    56. }
    57. public function process()
    58. {
    59. foreach ($this->pipes as $eachPipe) {
    60. //执行类方法
    61. $this->payLoad = call_user_func([
    62. $eachPipe,
    63. 'handle'
    64. ], $this->payLoad);
    65. }
    66. return $this->payLoad;
    67. }
    68. }
    69. //操作类
    70. class Test
    71. {
    72. public function run()
    73. {
    74. $payLoad = 10;
    75. $StageA = new StageA();
    76. $StageB = new StageB();
    77. $pipe = new Pipeline($payLoad);
    78. return $pipe->pipe($StageA)
    79. ->pipe($StageB)
    80. ->process();
    81. }
    82. }
    83. $test = new Test();
    84. echo '<pre>';
    85. var_dump($test->run());