搜索
首页后端开发php教程PHP设计模式之责任链模式的深入解析_PHP教程

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

Jul 21, 2016 pm 03:07 PM
php处理对象方法模式深入目的组织解析设计模式责任

责任链模式,其目的是组织一个对象链处理一个如方法调用的请求。
当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)一样传递下去。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327557.htmlTechArticle责任链模式,其目的是组织一个对象链处理一个如方法调用的请求。 当ConcreteHandler(具体的处理程序)不知道如何满足来自Client的请求时,...
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用PHP发送电子邮件的最佳方法是什么?使用PHP发送电子邮件的最佳方法是什么?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依赖注入的最佳实践PHP中依赖注入的最佳实践May 08, 2025 am 12:21 AM

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

PHP性能调整技巧和技巧PHP性能调整技巧和技巧May 08, 2025 am 12:20 AM

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

PHP电子邮件安全性:发送电子邮件的最佳实践PHP电子邮件安全性:发送电子邮件的最佳实践May 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

您如何优化PHP应用程序的性能?您如何优化PHP应用程序的性能?May 08, 2025 am 12:08 AM

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,数据库imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)优化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

PHP中的依赖注入是什么?PHP中的依赖注入是什么?May 07, 2025 pm 03:09 PM

依赖性注射inphpisadesignpatternthatenhancesFlexibility,可检验性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

最佳PHP性能优化技术最佳PHP性能优化技术May 07, 2025 pm 03:05 PM

PHP性能优化可以通过以下步骤实现:1)在脚本顶部使用require_once或include_once减少文件加载次数;2)使用预处理语句和批处理减少数据库查询次数;3)配置OPcache进行opcode缓存;4)启用并配置PHP-FPM优化进程管理;5)使用CDN分发静态资源;6)使用Xdebug或Blackfire进行代码性能分析;7)选择高效的数据结构如数组;8)编写模块化代码以优化执行。

PHP性能优化:使用OpCode缓存PHP性能优化:使用OpCode缓存May 07, 2025 pm 02:49 PM

opcodecachingsimplovesphperforvesphpermance bycachingCompiledCode,reducingServerLoadAndResponSetimes.1)itstorescompiledphpcodeinmemory,bypassingparsingparsingparsingandcompiling.2)useopcachebachebachebachebachebachebachebysettingparametersinphametersinphp.ini,likeememeryconmorysmorysmeryplement.33)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器