PHP design pattern Chain Of Responsibility (chain of responsibility pattern)_PHP tutorial

WBOY
Release: 2016-07-21 15:28:16
Original
795 people have browsed it

复制代码 代码如下:

/**
* Chain of Responsibility Pattern
*
* In order to decouple the sender and receiver of the request, multiple objects are used to process the request, connect these objects into a chain, and Pass the request along the chain until there is an object handling it
*
*/
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
";
} else {
$this->_handler->handleRequest($request);
}
}
}
class ConcreteHandlerOdd extends Handler
{
public function handleRequest($request)
{
if($request % 2)
{
echo $request." is odd
";
} else {
$this->_handler->handleRequest($request);
}
}
}
class ConcreteHandlerEven extends Handler
{
public function handleRequest($request)
{
if(!($request % 2))
{
echo $request." is even
";
} 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);
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323620.htmlTechArticle复制代码 代码如下: ?php /** * 职责链模式 * * 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这个请求,将这些对象连...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template