1. 程式人生 > 其它 >PHP實現責任鏈模式

PHP實現責任鏈模式

責任鏈模式就是指每個處理人決定它能處理哪些命令物件,當它無權處理時會把命令物件交下一個處理人,以下是php 實現責任鏈模式的程式碼

trait ResponsibilityMode
{
    protected $_level;
    protected $_nxt;
    //維持所有在責任鏈中的物件的權柄及其class name
    protected $_map = array(
        1 => 'Board',
        2 => 'Admin',
        3 => 'SuperAdmin',
        4 => 'Police'
); public final function __construct($level, $nxt) { //當前物件的Level $this->_level = $level; //當前物件的下一個物件的class name $this->_nxt = $this->_map[$nxt] ?? ""; } public final function process($lv = 1) { //判斷當前物件的權柄是否能夠處理 if ($lv <=
$this->_level) { echo $this->_map[$this->_level] . ' is processing this issue' . PHP_EOL; } else { //如果沒人能處理 if ($this->_nxt === "") { echo "sorry nobody can handle this issue!!!!"; exit; } //當前的權柄不夠,交給下一個人處理
$nxtCls = new $this->_nxt($this->_level + 1, $this->_level + 2); $nxtCls->process($lv); } } } class Board{use ResponsibilityMode;} class Admin{use ResponsibilityMode;} class SuperAdmin{use ResponsibilityMode;} class Police{use ResponsibilityMode;} $b = new SuperAdmin(3, 4); $b->process(4);

結果:
在這裡插入圖片描述