欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-27 17:15:06
复制代码 代码如下:
复制代码 代码如下:

<?php
/**
* 职责链模式
*
* 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它
*
*/
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);
}