Home >Backend Development >PHP Tutorial >Commonly used design patterns - chain of responsibility pattern and its PHP implementation

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

伊谢尔伦
伊谢尔伦Original
2016-12-01 11:44:151196browse

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);
?>


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