php管道模式Pipeline(也称流水线模式)

管道模式(也称流水线模式):对于管道模式(流水线模式)来说,有3个对象:管道,载荷,过滤器(阶段,阀门均可)。 
目的是在管道中对载荷进行一系列的处理。因为可以对过滤器进行动态的添加, 所以对载荷的处理可以变得更加灵活。但同时带来的问题是,在过滤器过多时, 很难把握整体的处理逻辑。而且在某一个过滤器对载荷处理后,因为载荷改变, 会造成下一个过滤器中的逻辑出错。 在示例中:管道类是Pipeline,载荷是在实例化Pipeline时传递的payLoad,过滤器是所有实现StageInterface的类。在web应用中,在服务器将请求分发给php的web入口文件到达具体处理请求的文件的周期中, 对request这个载荷的处理,可以应用管道模式(流水线模式)。

interface PipelineInterface
{

    public function __construct($payLoad);

    public function pipe(StageInterface $stage);

    public function process();
}

interface StageInterface
{

    public function handle($payLoad);
}

class StageAddHundred implements StageInterface
{

    public function handle($payLoad)
    {
        echo "StageAddHundred<pre>";
        return $payLoad + 100;
    }
}

class StageMultiHundred implements StageInterface
{

    public function handle($payLoad)
    {
        echo "StageMultiHundred<pre>";
        return $payLoad * 100;
    }
}

class Pipeline implements PipelineInterface
{

    private $pipes;

    private $payLoad;

    public function __construct($payLoad)
    {
        $this->payLoad = $payLoad;
    }

    public function pipe(StageInterface $stage)
    {
        $this->pipes[] = $stage;
        return $this;
    }

    public function process()
    {
        foreach ($this->pipes as $eachPipe) {
            $this->payLoad = call_user_func([
                $eachPipe,
                'handle'
            ], $this->payLoad);
        }
        
        return $this->payLoad;
    }
}

class Test
{

    public function run()
    {
        $payLoad = 10;
        
        $stageAddHundred = new StageAddHundred();
        $stageMultiHundred = new StageMultiHundred();
        
        $pipe = new Pipeline($payLoad);
        
        return $pipe->pipe($stageAddHundred)
            ->pipe($stageMultiHundred)
            ->process();
    }
}

$test = new Test();

echo '<pre>';
var_dump($test->run());

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅坞茶坊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值