複製代碼 代碼如下:<?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);
}