美文网首页
职责链模式

职责链模式

作者: 散装咖啡 | 来源:发表于2017-05-30 03:03 被阅读15次
    /**
    * chainOfResponsibility模式
    *
    * 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这
    个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理
    它
    *
    */
        abstract class Handler
        {
            protected $_handler = null;
            
            public function setSuccessor($handler)
            {
                $this->_handler =$handler;
            }
            
            abstract function handleRequest($request);
        }
        
        class ConcreteHandlerZero extends Handler
        {
            public function handleRequest($request)
            {
                if ($request==0) {
                    echo "0<br/>";
                } else {
                    $this->_handler->handleRequest($request);
                }
            }
        }
        
        class ConcreteHandlerOdd extends Handler
        {
            public function handleRequest($request)
            {
                if ($request%2) {
                    echo $request . " is odd<br/>";
                } else {
                    $this->_handler->handleRequest($request);
                }
            }
        }
        
        class ConcreteHandlerEven extends Handler
        {
            public function handleRequest($request)
            {
                if (!($request%2)) {
                    echo $request . " is even<br/>";
                } else {
                    $this->_handler->handleRequest($request);
                }
            }
        }
        
    // 实例一下
    $objZeroHander = new ConcreteHandlerZero();
    $objEvenHander = new ConcreteHandlerEven();
    $objOddHander = new ConcreteHandlerOdd();
    $objZeroHander->setSuccessor($objEvenHander);
    $objEvenHander->setSuccessor($objOddHander);
    foreach(array(2,3,4,5,0) as $row)
    {
    $objZeroHander->handleRequest($row);
    }
    

    参考文章 https://wenku.baidu.com/view/b4c78b4702768e9951e738fb.html

    相关文章

      网友评论

          本文标题:职责链模式

          本文链接:https://www.haomeiwen.com/subject/kjglfxtx.html