首页 >后端开发 >php教程 >php设计模式 Chain Of Responsibility (职责链模式)_PHP

php设计模式 Chain Of Responsibility (职责链模式)_PHP

WBOY
WBOY原创
2016-06-01 12:15:56726浏览
复制代码 代码如下:
/**
* 职责链模式
*
* 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它
*
*/
抽象类 Handler
{
protected $_handler = null;
public function setSuccessor($handler)
{
$this->_handler = $handler;
}
抽象函数handleRequest($request);
}
class ConcreteHandlerZero 扩展处理程序
{
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." 很奇怪
";
} else {
$this->_handler->handleRequest($request);
}
}
}
class ConcreteHandlerEven extends Handler
{
public function handleRequest($request)
{
if(!($request % 2))
{
echo $request." 是偶数
";
} 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);
}
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn