PHP设计模式之责任链模式的深入解析


Posted in PHP onJune 13, 2013

责任链模式,其目的是组织一个对象链处理一个如方法调用的请求。
当ConcreteHandler(具体的处理程序)不知道如何满足来自Client的请求时,或它的目的不是这个时,它会委派给链中的下一个Handler(处理程序)来处理。

这个设计模式通常和复合模式一起使用,其中有些叶子或容器对象默认委派操作给它们的父对象。另一个例子是,本地化通常是使用责任链处理的,当德语翻译适配器没有为翻译关键词找到合适的结果时,就返回到英语适配器或干脆直接显示关键词本身。

耦合减少到最低限度:Client类不知道由哪个具体的类来处理请求;在创建对象图时配置了链;ConcreteHandlers不知道哪个对象是它们的继承者。行为在对象之间分配是成功的,链中最近的对象有优先权和责任满足请求。

参与者:
◆Client(客户端):向Handler(处理程序)提交一个请求;
◆Handler(处理程序)抽象:接收一个请求,以某种方式满足它;
◆ConcreteHandlers(具体的处理程序):接收一个请求,设法满足它,如果不成功就委派给下一个处理程序。
下面的代码实现了一个最著名的责任链示例:多级缓存。

/**  
 * The Handler abstraction. Objects that want to be a part of the  
 * ChainOfResponsibility must implement this interface directly or via  
 * inheritance from an AbstractHandler.  
 */ 
interface KeyValueStore  
{  
    /**  
     * Obtain a value.  
     * @param string $key  
     * @return mixed  
     */ 
    public function get($key);  
}  /**  
 * Basic no-op implementation which ConcreteHandlers not interested in  
 * caching or in interfering with the retrieval inherit from.  
 */ 
abstract class AbstractKeyValueStore implements KeyValueStore  
{  
    protected $_nextHandler;  
    public function get($key)  
    {  
 return $this->_nextHandler->get($key);  
    }  
}  
/**  
 * Ideally the last ConcreteHandler in the chain. At least, if inserted in  
 * a Chain it will be the last node to be called.  
 */ 
class SlowStore implements KeyValueStore  
{  
    /**  
     * This could be a somewhat slow store: a database or a flat file.  
     */ 
    protected $_values;  
    public function __construct(array $values = array())  
    {  
 $this->_values = $values;  
    }  
    public function get($key)  
    {  
 return $this->_values[$key];  
    }  
}  
/**  
 * A ConcreteHandler that handles the request for a key by looking for it in  
 * its own cache. Forwards to the next handler in case of cache miss.  
 */ 
class InMemoryKeyValueStore implements KeyValueStore  
{  
    protected $_nextHandler;  
    protected $_cached = array();  
    public function __construct(KeyValueStore $nextHandler)  
    {  
 $this->_nextHandler = $nextHandler;  
    }  
    protected function _load($key)  
    {  
 if (!isset($this->_cached[$key])) {  
     $this->_cached[$key] = $this->_nextHandler->get($key);  
 }  
    }  
    public function get($key)  
    {  
 $this->_load($key);  
 return $this->_cached[$key];  
    }  
}  
/**  
 * A ConcreteHandler that delegates the request without trying to  
 * understand it at all. It may be easier to use in the user interface  
 * because it can specialize itself by defining methods that generates  
 * html, or by addressing similar user interface concerns.  
 * Some Clients see this object only as an instance of KeyValueStore  
 * and do not care how it satisfy their requests, while other ones  
 * may use it in its entirety (similar to a class-based adapter).  
 * No client knows that a chain of Handlers exists.  
 */ 
class FrontEnd extends AbstractKeyValueStore  
{  
    public function __construct(KeyValueStore $nextHandler)  
    {  
 $this->_nextHandler = $nextHandler;  
    }  
    public function getEscaped($key)  
    {  
 return htmlentities($this->get($key), ENT_NOQUOTES, 'UTF-8');  
    }  
}  
// Client code  
$store = new SlowStore(array('pd' => 'Philip K. Dick',  
 'ia' => 'Isaac Asimov',  
 'ac' => 'Arthur C. Clarke',  
 'hh' => 'Helmut Heißenbüttel'));  
// in development, we skip cache and pass $store directly to FrontEnd  
$cache = new InMemoryKeyValueStore($store);  
$frontEnd = new FrontEnd($cache);  
echo $frontEnd->get('ia'), "\n";  
echo $frontEnd->getEscaped('hh'), "\n";

关于PHP责任链设计模式的一些实现说明:
◆责任链可能已经存在于对象图中,和复合模式的例子一样;
◆此外,Handler抽象可能存在,也可能不存在,最好的选择是一个分开的Handler接口只可以执行handleRequest()操作,不要强制一个链只在一个层次中,因为后面的已经存在了;
◆也可能引入一个抽象类,但由于请求处理是一个正交关注,因此具体的类可能已经继承了其它类;
◆通过constructor 或setter,Handler(或下一个Handler)被注入到Client或前一个Handler;
◆请求对象通常是一个ValueObject,也可能被实现为一个Flyweight,在PHP中,它可能是一个标量类型,如string,注意在某些语言中,一个string就是一个不变的ValueObject。

简单的总结责任链模式,可以归纳为:用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合,唯一共同点是在他们之间传递request. 也就是说,来了一个请求,A类先处理,如果没有处理,就传递到B类处理,如果没有处理,就传递到C类处理,就这样象一个链条(chain)一样传递下去。

PHP 相关文章推荐
使用无限生命期Session的方法
Oct 09 PHP
社区(php&&mysql)五
Oct 09 PHP
PHP整数取余返回负数的相关解决方法
May 15 PHP
Thinkphp实现MySQL读写分离操作示例
Jun 25 PHP
成为好程序员必须避免的5个坏习惯
Jul 04 PHP
php实现的树形结构数据存取类实例
Nov 29 PHP
php操作(删除,提取,增加)zip文件方法详解
Mar 12 PHP
PHP贪婪算法解决0-1背包问题实例分析
Mar 23 PHP
php数组合并与拆分实例分析
Jun 12 PHP
PHP基于imagick扩展实现合成图片的两种方法【附imagick扩展下载】
Nov 14 PHP
php实现微信公众平台发红包功能
Jun 14 PHP
PHP生成二维码与识别二维码的方法详解【附源码下载】
Mar 07 PHP
PHP设计模式之结构模式的深入解析
Jun 13 #PHP
PHP设计模式之命令模式的深入解析
Jun 13 #PHP
深入Memcache的Session数据的多服务器共享详解
Jun 13 #PHP
探讨:如何使用PHP实现计算两个日期间隔的年、月、周、日数
Jun 13 #PHP
判断php数组是否为索引数组的实现方法
Jun 13 #PHP
深入解析yii权限分级式访问控制的实现(非RBAC法)
Jun 13 #PHP
PHP 基于Yii框架中使用smarty模板的方法详解
Jun 13 #PHP
You might like
发布一个用PHP fsockopen写的HTTP下载的类
2007/02/22 PHP
discuz7 phpMysql操作类
2009/06/21 PHP
php 取得瑞年与平年的天数的代码
2009/08/10 PHP
PHP中json_encode、json_decode与serialize、unserialize的性能测试分析
2010/06/09 PHP
thinkPHP实现签到功能的方法
2017/03/15 PHP
js解析与序列化json数据(一)json.stringify()的基本用法
2013/02/01 Javascript
利用javaScript实现点击输入框弹出窗体选择信息
2013/12/11 Javascript
php析构函数的具体用法小结
2014/03/11 Javascript
jQuery使用serialize()表单序列化时出现中文乱码问题的解决办法
2016/07/27 Javascript
JavaScript编码风格指南(中文版)
2016/08/26 Javascript
bootstrap table小案例
2016/10/21 Javascript
NodeJS处理Express中异步错误
2017/03/26 NodeJs
JS jQuery使用正则表达式去空字符的简单实现代码
2017/05/20 jQuery
Angular X中使用ngrx的方法详解(附源码)
2017/07/10 Javascript
jquery自定义显示消息数量
2017/12/19 jQuery
利用JavaScript缓存远程窃取Wi-Fi密码的思路详解
2018/11/05 Javascript
深入解析Python中的上下文管理器
2016/06/28 Python
Python实现的json文件读取及中文乱码显示问题解决方法
2018/08/06 Python
Flask框架中request、请求钩子、上下文用法分析
2019/07/23 Python
Python数学形态学实例分析
2019/09/06 Python
Python的缺点和劣势分析
2019/11/19 Python
python 微信好友特征数据分析及可视化
2020/01/07 Python
python字典和json.dumps()的遇到的坑分析
2020/03/11 Python
VSCode配合pipenv搞定虚拟环境的实现方法
2020/05/17 Python
django使用graphql的实例
2020/09/02 Python
html5-canvas中使用clip抠出一个区域的示例代码
2018/05/25 HTML / CSS
丝芙兰美国官网:SEPHORA美国
2016/08/03 全球购物
美国现代家具购物网站:LexMod
2019/01/09 全球购物
财务管理专业自荐信范文
2013/12/24 职场文书
工程业务员岗位职责
2013/12/31 职场文书
社区庆八一活动方案
2014/02/02 职场文书
教师工作表现自我评价
2015/03/05 职场文书
教师求职信怎么写
2015/03/20 职场文书
地雷战观后感
2015/06/09 职场文书
Python基础之字符串格式化详解
2021/04/21 Python
MySQL 隔离数据列和前缀索引的使用总结
2021/05/14 MySQL