专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

PHP 实现责任链模式

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

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

65_1.png

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);
}

文章永久链接:https://tech.souyunku.com/45218

未经允许不得转载:搜云库技术团队 » PHP 实现责任链模式

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们