php设计模式 Chain Of Responsibility (职责链模式)
程序员文章站
2022-05-31 09:26:38
复制代码 代码如下:
<?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);
}
复制代码 代码如下:
<?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);
}
上一篇: 火车上的沉思
下一篇: php URL跳转代码 减少外链