Home >Backend Development >PHP Tutorial >Commonly used design patterns - chain of responsibility pattern and its PHP implementation
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
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); ?>