php设计模式 Chain Of Responsibility (职责链模式)
/**
* 职责链模式
*
* 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它
*
*/
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);
}
推荐阅读
-
php设计模式 Chain Of Responsibility (职责链模式)
-
php设计模式 Chain Of Responsibility (职责链模式)_PHP
-
设计模式之Chain of Responsibility(责任链)
-
PHP常用设计模式单例, 工厂, 观察者, 责任链, 装饰, 策略,适配,桥接模式
-
javascript设计模式 – 职责链模式原理与用法实例分析
-
PHP 设计模式系列 -- 责任链模式(Chain Of Responsibilities)
-
浅谈php设计模式之责任链模式
-
C#设计模式之ChainOfResponsibility职责链模式解决真假美猴王问题实例
-
C#设计模式之ChainOfResponsibility职责链模式解决真假美猴王问题实例
-
iOS应用设计模式开发中职责链(责任链)模式的实现解析