Commonly used design patterns - chain of responsibility pattern and its PHP implementation

伊谢尔伦
Release: 2023-03-02 18:26:01
Original
1180 people have browsed it

The chain of responsibility model is a behavioral model, which contains some command objects and a series of processing objects. Each handler object determines which command objects it can handle, and it also knows how to pass command objects it cannot handle to the next handler object in the chain. The pattern also describes methods for adding new processing objects to the end of the processing chain.

Main roles

Abstract Responsibility role: Defines the public methods supported by all responsibilities.

Concrete Responsibility role: Concrete responsibility implemented with abstract responsibility interface

Chain of responsibility role: Set the calling rules of responsibility

Class diagram

Commonly used design patterns - chain of responsibility pattern and its PHP implementation

Instance

<?php
abstract class Responsibility { // 抽象责任角色
    protected $next; // 下一个责任角色
 
    public function setNext(Responsibility $l) {
        $this->next = $l;
        return $this;
    }
    abstract public function operate(); // 操作方法
}
 
class ResponsibilityA extends Responsibility {
    public function __construct() {}
    public function operate(){
        if (false == is_null($this->next)) {
            $this->next->operate();
        }
    };
}
class ResponsibilityB extends Responsibility {
    public function __construct() {}
    public function operate(){
        if (false == is_null($this->next)) {
            $this->next->operate();
        }
    };
}
 
$res_a = new ResponsibilityA();
$res_b = new ResponsibilityB();
$res_a->setNext($res_b);
?>
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!