【PHP-設計模式】職責鏈模式
阿新 • • 發佈:2018-11-27
author:咔咔
WeChat:fangkangfk
什麼是職責鏈模式:
職責鏈模式是包含了一些命令物件和一些處理物件,每個處理物件決定他能處理的那些命令物件,它也知道把自己不能處理的命令物件移交給下一個處理物件
白話解釋:
這個案例一共三個職位,是經理,總監,總經理,職位就類似命令物件,請假這件事就類似命令物件,當經理處理不了的事情就需要移交給總監,總監處理的不了的事情就需要移交給總經理,這也就是我們的職責鏈模式
下來我們分段來解釋這個案例
首先這個案例分為三部分第一部分是宣告的屬性,第二部分是抽象類裡邊設定上下級關係,抽象方法,第三部分就是業務方面的程式碼
在抽象類manage這個類中apply抽象方法中注入了request這個類
當請假數量大於2的時候經理的職權就不夠了,這個時候就會走apply這個方法,this->manage這個屬性是獲取的對應職位的上級的類,然後在呼叫自己的處理函式方法完成邏輯處理,如還沒有許可權則繼續追尋上級,直到許可權滿足返回處理結果即可
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/11/26 * Time: 14:04 */ //申請Model class Request { //數量 public $num; //申請型別 public $requestType; //申請內容 public $requestContent; } //抽象管理者 abstract class Manager { protected $name; //管理者上級 protected $manager; public function __construct($_name) { $this->name = $_name; } //設定管理者上級 public function SetHeader(Manager $_mana) { $this->manager = $_mana; } //申請請求 abstract public function Apply(Request $_req); } //經理 class CommonManager extends Manager { public function __construct($_name) { parent::__construct($_name); } public function Apply(Request $_req) { if($_req->requestType=="請假" && $_req->num<=2) { echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批准。<br/>"; } else { if(isset($this->manager)) { $this->manager->Apply($_req); } } } } //總監 class MajorDomo extends Manager { public function __construct($_name) { parent::__construct($_name); } public function Apply(Request $_req) { if ($_req->requestType == "請假" && $_req->num <= 5) { echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批准。<br/>"; } else { if (isset($this->manager)) { $this->manager->Apply($_req); } } } } //總經理 class GeneralManager extends Manager { public function __construct($_name) { parent::__construct($_name); } public function Apply(Request $_req) { if ($_req->requestType == "請假") { echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批准。<br/>"; } else if($_req->requestType=="加薪" && $_req->num <= 500) { echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批准。<br/>"; } else if($_req->requestType=="加薪" && $_req->num>500) { echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}再說吧。<br/>"; } } } header("Content-Type:text/html;charset=utf-8"); //--------------------職責鏈模式---------------------- $jingli = new CommonManager("李經理"); $zongjian = new MajorDomo("郭總監"); $zongjingli = new GeneralManager("孫總"); //設定直接上級 $jingli->SetHeader($zongjian); $zongjian->SetHeader($zongjingli); //申請 $req1 = new Request(); $req1->requestType = "請假"; $req1->requestContent = "小菜請假!"; $req1->num = 20; $jingli->Apply($req1);