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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

<?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密码生成类实例

本文实例讲述了php实现的密码生成类及其应用方法,分享给大家供大家参考。具体分析如下: 一、php密码生成类功能: 1.可设定密码长度。 2.可设定要生成的密码个数,批量生成。 3.可以...

php使用wordwrap格式化文本段落的方法

本文实例讲述了php使用wordwrap格式化文本段落的方法。分享给大家供大家参考。具体分析如下: wordwrap()函数可以按照指定的固定行长度格式化文本段落,让段落看起来更加整齐...

php使用正则表达式获取图片url的方法

本文实例讲述了php使用正则表达式获取图片url的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下: <?php header("Content-typ...

深入php数据采集的详解

这里介绍两个php采集能用到的好工具。一个是Snoopy,一个是simple_html_dom。采集还有很多方式(其实本质就2-3种,其他的都是衍生的),php自带了几个方法也能直接进行...

php中的登陆login

login <?php require "../include/DBClass.php"; $username=$_POST['UserName']; $password...