search
HomeBackend DevelopmentPHP Tutorial简单介绍PHP的责任链编程模式_PHP

概述
责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态的重新组织和分配责任

责任链模式的定义
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间耦合关系,将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
 
责任链模式的优点
最为显著的优点就是将请求和处理分开。请求者可以不用知道是谁处理的,处理者可以不用知道请求的全貌,两者解耦,提高系统的灵活性。
  
责任链模式的缺点
一是性能问题,每个请求都是从链头遍历到链尾,特别是在链比较长的时候,性能是一个问题。二是调试不是很方便,特别是链条比较长的,环节比较多的时候,由于采用了类似递归的方式 ,调试的时候逻辑可能比较复杂。

责任链模式涉及到的角色如下:

    抽象处理者(Handler)角色:定义出一个处理请求的接口。如果需要,接口可以定义出一个方法以设定和返回对下家的引用。这个角色通常由一个php的抽象类或接口实现。上图中Handler类的聚合关系给出了具体子类对下家的引用,抽象方法handleRequest()规范了子类处理请求的操作
    具体处理者(ConcreateHandle)角色:具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理这可以访问下家


来看一个PHP的责任链模式编程实例:
 

  <&#63;php 
   
  /** 
   * 抽象处理者角色 
   * @author wzy 
   * 
   */ 
  abstract class Handle 
  { 
   
    /** 
     * 持有后继的责任对象 
     * 
     * @var object 
     */ 
    protected $successor; 
   
    /** 
     * 示意处理请求的方法,虽然这个示意方法是没有传入参素的 
     * 但实际是可以传入参数的,根据具体需要来选择是否传递参数 
     */ 
    public abstract function handleRequest (); 
   
    /** 
     * 取值方法 
     * 
     * @return object 
     */ 
    public function getSuccessor () 
    { 
      return $this->successor; 
    } 
   
    /** 
     * 赋值方法,设置后继的责任对象 
     * 
     * @param object $objsuccessor       
     */ 
    public function setSuccessor ($objsuccessor) 
    { 
      $this->successor = $objsuccessor; 
    } 
  } 
   
  /** 
   * 具体处理者角色 
   * 
   * @author wzy 
   *     
   */ 
  class ConcreateHandler extends Handle 
  { 
   
    /** 
     * 判断是否有后继的责任对象 
     * 如果有,就转发请求给后继的责任对象 
     * 如果没有,则处理请求 
     * 
     * @see Handle::handleRequest() 
     */ 
    public function handleRequest () 
    { 
      if ($this->getSuccessor() != null) { 
        echo "放过请求,将请求转发给后继的责任对象!<br>"; 
        $this->getSuccessor()->handleRequest(); 
      } else { 
        echo "处理请求,处理过程省略...<br>"; 
      } 
    } 
  } 
   
  /** 
   * 客户端代码 
   */ 
   
  // 组装责任链 
  $handle1 = new ConcreateHandler(); 
  $handle2 = new ConcreateHandler(); 
  $handle1->setSuccessor($handle2); 
   
  // 提交请求 
  $handle1->handleRequest(); 
  &#63;> 


通过代码可以看出,客户端创建了两个处理者对象,并指定第一个处理者对象的下家是第二个处理者对象,而第二个处理者对象却没有下家。然后客户端将请求传递给第一个处理者对象

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

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

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor