PHP设计模式——责任链模式

<?php

/**
 * 责任链模式
 * 组织一个对象链处理一个请求,每个处理对象知道自己能处理哪些请求,并把自己不能处理的请求交下一个处理对象
 * 
 *  适用场景:          
 *  1、有多个对象可以处理同一个请求,具体哪个对象处理该请求由运行时刻自动确定。
 *  2、在不明确指定接收者的情况下,向多个对象中的一个提交一个请求。
 */
abstract class Handler {

    protected $_power = NULL;

    abstract public function process($lev);
}

class Level1 extends Handler {

    protected $_power = 10;
    protected $_top = 'Level2';

    public function process($lev) {
        if ($lev <= $this->_power) {
            echo '处理级别:Level1(~10)<br>';
            return;
        }
        $top = new $this->_top;
        $top->process($lev);
    }

}

class Level2 extends Handler {

    protected $_power = 100;
    protected $_top = 'Level3';

    public function process($lev) {
        if ($lev <= $this->_power) {
            echo '处理级别:Level2(11~100)<br>';
            return;
        }
        $top = new $this->_top;
        $top->process($lev);
    }

}

class Level3 extends Handler {

    protected $_power;
    protected $_top = NULL;

    public function process($lev) {
        echo '处理级别:Level3(100~)<br>';
        return;
    }

}

/**
 * 测试用例
 */
$handler = new Level1();
echo '测试1:';
$handler->process(1);
echo '测试11:';
$handler->process(11);
echo '测试111:';
$handler->process(111);
原文地址:https://www.cnblogs.com/tlxma/p/5210702.html