search
HomeBackend DevelopmentPHP TutorialPhp design patterns: behavioral patterns (3)

7. Chain of Responsibility:

Multiple objects have the opportunity to process requests, decoupling the request sender and receiver. Just like a cash machine in a bank, you can withdraw money from any machine.

Benefits: Simplify the object hidden chain structure, making it easy to add new responsibility nodes.

Disadvantages: The request may have no receiver, or be called by multiple receivers, resulting in reduced performance.

Application scenario: Handle multiple requests.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 职责链模式 Chain of Responsibility
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
/** 
 * 加入在公司里,如果你的请假时间小于0.5天,那么只需要向leader打声招呼就OK了。 
  如果0.5<=请假天数<=3天,需要先leader打声招呼,然后部门经理签字。 
  如果3<请假天数,需要先leader打声招呼,然后到部门经理签字,最后总经经理确认签字, 
    如果请假天数超过10天,是任何人都不能批准的。
 */ 
  
/** 
 * 抽象处理者角色(Handler:Approver):定义一个处理请求的接口,和一个后继连接(可选) 
 * 
 */  
abstract class Handler 
{  
    protected $_handler = null;  
    protected $_handlerName = null;  
      
    public function setSuccessor($handler)  
    {  
        $this->_handler = $handler;  
    }  
      
    protected  function _success($request)  
    {  
        output(sprintf("%s&#39;s request was passed", $request->getName())); 
        return true;  
    }  
    abstract function handleRequest($request);  
}  
/** 
 * 具体处理者角色(ConcreteHandler:President):处理它所负责的请求,可以访问后继者,如果可以处理请求则处理,否则将该请求转给他的后继者。 
 * 
 */  
class ConcreteHandlerLeader extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
    public function handleRequest($request)  
    {  
        if($request->getDay() < 0.5) {  
            output(sprintf(&#39;%s was told&#39;, $this->_handlerName));       // 已经跟leader招呼了
            return $this->_success($request);  
        }   
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        }  
    }  
}  
/** 
 * Manager 
 * 
 */  
class ConcreteHandlerManager extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
      
    public function handleRequest($request)  
    {  
        if(0.5 <= $request->getDay() && $request->getDay()<=3) {  
            output(sprintf(&#39;%s signed&#39;, $this->_handlerName));       // 部门经理签字
            return $this->_success($request);  
        }   
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        }  
    }  
}  
class ConcreteHandlerGeneralManager extends Handler  
{  
    function __construct($handlerName){  
        $this->_handlerName = $handlerName;  
    }  
      
    public function handleRequest($request)  
    {  
        if(3 < $request->getDay() && $request->getDay() < 10){  
            output(sprintf(&#39;%s signed&#39;, $this->_handlerName));       // 总经理签字
            return $this->_success($request);  
        }  
        if ($this->_handler instanceof Handler) {  
            return $this->_handler->handleRequest($request);  
        } else {
            output(sprintf(&#39;no one can approve request more than 10 days&#39;));
        }
    }  
}  
/** 
 * 请假申请 
 * 
 */  
class Request  
{  
    private $_name;  
    private $_day;  
    private $_reason;  
  
    function __construct($name= &#39;&#39;, $day= 0, $reason = &#39;&#39;){  
        $this->_name = $name;  
        $this->_day = $day;  
        $this->_reason = $reason;  
    }  
      
    public function setName($name){  
        $this->_name = $name;  
    }  
    public function getName(){  
        return  $this->_name;  
    }  
      
    public function setDay($day){  
        $this->_day = $day;  
    }  
    public function getDay(){  
        return  $this->_day ;  
    }  
      
    public function setReason($reason ){  
         $this->_reason = $reason;  
    }  
    public function getReason( ){  
        return  $this->_reason;  
    }  
}  
  
  
class Client {  
      
    public static function test(){  
          
        $leader = new ConcreteHandlerLeader(&#39;leader&#39;);  
        $manager = new ConcreteHandlerManager(&#39;manager&#39;);  
        $generalManager = new ConcreteHandlerGeneralManager(&#39;generalManager&#39;);  
          
        //请求实例  
        $request = new Request(&#39;ucai&#39;,4,&#39;休息&#39;);  
          
        $leader->setSuccessor($manager);  
        $manager->setSuccessor($generalManager);  
        $result =  $leader->handleRequest($request);  
    }  
      
}  
  
Client::test();

8. Strategy pattern:

Define a series of algorithms, encapsulate each algorithm, and make them interchangeable. Just like the players on a basketball team, on and off the court. The coach can let those on the field come down, and he can also let those off the field play.

Benefits: Define a series of reusable algorithms and behaviors, and eliminate if else statements.

Disadvantage: The calling end must know all strategy classes.

Application scenario: Used for replacement between objects.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 策略模式 Strategy
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
//策略基类接口
interface IStrategy {
    public function OnTheWay();
}
class WalkStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上步行&#39;);
    }
}
class RideBickStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上骑自行车&#39;);
    }
}
class CarStrategy implements IStrategy {
    public function OnTheWay() {
        output( &#39;在路上开车&#39;);
    }
}
//选择策略类Context
class Context {
    public function find($strategy) {
        $strategy->OnTheWay();
    }
}
class Client {  
      
    public static function test(){  
        $travel = new Context();
        $travel->find(new WalkStrategy());
        $travel->find(new RideBickStrategy());
        $travel->find(new CarStrategy());
    }  
      
}  
  
Client::test();

Known modes

1. Memento mode (Memento):

Save the state of the object at a moment. Dear, do you still remember that deskmate who said, "Please call me when the teacher is here"?

Benefits: Provides users with a mechanism to restore their status.

Disadvantages: Consumption of resources.

Application scenario: used for data that needs to be saved.

Code implementation:

<?php
/**
 * 优才网公开课示例代码
 *
 * 备忘录模式 Memento
 *
 * @author 优才网全栈工程师教研组
 * @see http://www.ucai.cn
 */
function output($string) {
    echo    $string . "\n";
}
class Originator { // 发起人(Originator)角色
    private $_state;
    public function __construct() {
        $this->_state = &#39;&#39;;
    }
    public function createMemento() { // 创建备忘录
        return new Memento($this->_state);
    }
    public function restoreMemento(Memento $memento) { // 将发起人恢复到备忘录对象记录的状态上
        $this->_state = $memento->getState();
    }
    public function setState($state) { $this->_state = $state; } 
    public function getState() { return $this->_state; }
    public function showState() {
        output($this->_state);
    }
}
class Memento { // 备忘录(Memento)角色 
    private $_state;
    public function __construct($state) {
        $this->setState($state);
    }
    public function getState() { return $this->_state; } 
    public function setState($state) { $this->_state = $state;}
}
class Caretaker { // 负责人(Caretaker)角色 
    private $_memento;
    public function getMemento() { return $this->_memento; } 
    public function setMemento(Memento $memento) { $this->_memento = $memento; }
}
class Client {  
      
    public static function test(){  
        $org = new Originator();
        $org->setState(&#39;open&#39;);
        $org->showState();
        /* 创建备忘 */
        $memento = $org->createMemento();
        /* 通过Caretaker保存此备忘 */
        $caretaker = new Caretaker();
        $caretaker->setMemento($memento);
        /* 改变目标对象的状态 */
        $org->setState(&#39;close&#39;);
        $org->showState();
        /* 还原操作 */
        $org->restoreMemento($caretaker->getMemento());
        $org->showState();
    }  
      
}  
  
Client::test(); 
return;
try {
    $db->beginTransaction();
    $succ   = $db->exec($sql_1);
    if (!$succ) {
        throw new Exception(&#39;SQL 1 update failed&#39;);
    }
    $succ   = $db->exec($sql_2);
    if (!$succ) {
        throw new Exception(&#39;SQL 2 update failed&#39;);
    }
    $succ   = $db->exec($sql_3);
    if (!$succ) {
        throw new Exception(&#39;SQL 3 update failed&#39;);
    }
    $db->commit();
} catch (Exception $exp) {
    $db->rollBack();
}

Deep mode

1. Interpreter mode (Interpreter):

Define the grammar of the language and build an interpreter to interpret sentences in the language. Every kid who has used a dictionary knows this.

Advantages: Good scalability and flexibility.

Disadvantages: It may be difficult to maintain complex grammars.

Application scenario: Used for pair or one-to-many requirements.

2. Visitor mode:

Encapsulates certain operations that act on each element in a certain data structure. You can define new operations that act on these elements without changing the data structure. Such as bank numbering machine.

Benefits: Concentrate related things into a visitor object.

Disadvantages: It is difficult to add new data structures.

Application scenarios: Queuing, numbering.

3. Summary

This article introduces behavioral patterns. Behavioral patterns involve the allocation between algorithms and object responsibilities. Behavioral class patterns use inheritance mechanisms to assign behaviors between classes. TemplateMethod and Interpreter are class behavior patterns. . Behavioral object patterns use object composition instead of inheritance. Some behavioral object patterns describe how a group of peer objects cooperate with each other to complete tasks that no one object can complete alone. For example, Mediator introduces a mediator object between objects to provide Indirectness required for loose coupling; Chain of Responsibility provides looser coupling. It implicitly sends a loose request to an object through a candidate object chain, and can determine which candidates participate in the chain at runtime; Observer defines and maintains Dependencies between objects; other behavioral object patterns often encapsulate behavior in an object and assign requests to it. Strategy pattern encapsulates algorithms in objects, so that aspects can be changed and specified by an object. Algorithm; Command mode encapsulates the request in an object so that it can be passed as a parameter and can be stored in a history list or used in other ways; State mode encapsulates the state of an object so that when the object's state object changes , the object can change its behavior; the Visitor pattern encapsulates the behavior distributed among multiple classes; and the Iterator pattern abstracts the way to access and traverse objects in a collection.


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft