PHP 实现责任链模式

326 阅读1分钟

试用场景 多个对象可以处理同一个请求,具体是哪一个对象处理该请求由运行时刻自动决定;

角色分析:
1、抽象处理者(handler)角色
2、具体处理者(handler)角色
3、客户类角色

abstract class Handler
{
    protected $_nextHandler;

    public function getNextHandler()
    {
        return $this->_nextHandler;
    }

    public function setNextHandler(Handler $nextHandler)
    {
        $this->_nextHandler = $nextHandler;
    }

    abstract function handleMessage(int $type);
}

class ConcreteHandler1 extends Handler
{
    public function handleMessage(int $type)
    {
        if($type % 2 == 0) {
            echo "ConcreteHandler1 solved the problems".PHP_EOL;
        } else {
            echo "ConcreteHandler1 can not solved the problems".PHP_EOL;
            if($this->_nextHandler != null) {
                $this->_nextHandler->handleMessage($type);
            } else {
                echo "no one can solve the problem!".PHP_EOL;
            }
        }
    }
}


class ConcreteHandler2 extends Handler
{
    public function handleMessage(int $type)
    {
        if($type % 5 == 0) {
            echo "ConcreteHandler2 solved the problems".PHP_EOL;
        } else {
            echo "ConcreteHandler2 can not solved the problems".PHP_EOL;
            if($this->_nextHandler != null) {
                $this->_nextHandler->handleMessage($type);
            } else {
                echo "no one can solve the problem!".PHP_EOL;
            }
        }
    }
}


class ConcreteHandler3 extends Handler
{
    public function handleMessage(int $type)
    {
        if($type % 3 == 0) {
            echo "ConcreteHandler3 solved the problems".PHP_EOL;
        } else {
            echo "ConcreteHandler3 can not solved the problems".PHP_EOL;
            if($this->_nextHandler != null) {
                $this->_nextHandler->handleMessage($type);
            } else {
                echo "no one can solve the problem!".PHP_EOL;
            }
        }
    }
}

$handler1 = new ConcreteHandler1();
$handler2 = new ConcreteHandler2();
$handler3 = new ConcreteHandler3();
$handler1->setNextHandler($handler2);
$handler2->setNextHandler($handler3);
for ($i = 0; $i < 10; $i++) {
    echo "proceeding message...".$i.PHP_EOL;
    $handler1->handleMessage($i);
}