1. 程式人生 > >職責鏈模式 - 設計模式 - PHP版

職責鏈模式 - 設計模式 - PHP版

sse man article manage pre 直接 nbsp eth protect

  1 <?php
  2 /*
  3  * 職責鏈模式
  4  * 
  5  * 參考:http://blog.csdn.net/jhq0113/article/details/46454419
  6  * 
  7  */
  8 //申請Model  
  9 class Request {
 10     //數量  
 11     public $num;
 12     //申請類型  
 13     public $requestType;
 14     //申請內容  
 15     public $requestContent;
 16 }
 17 //抽象管理者  
18 abstract class Manager { 19 protected $name; 20 //管理者上級 21 protected $manager; 22 public function __construct($_name) { 23 $this->name = $_name; 24 } 25 //設置管理者上級 26 public function SetHeader(Manager $_mana) { 27 $this->manager = $_mana
; 28 } 29 //申請請求 30 abstract public function Apply(Request $_req); 31 } 32 //經理 33 class CommonManager extends Manager { 34 public function __construct($_name) { 35 parent::__construct($_name); 36 } 37 public function Apply(Request $_req) { 38 if
($_req->requestType == "請假" && $_req->num <= 2) { 39 echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批準。<br/>"; 40 } else { 41 if (isset($this->manager)) { 42 $this->manager->Apply($_req); 43 } 44 } 45 } 46 } 47 //總監 48 class MajorDomo extends Manager { 49 public function __construct($_name) { 50 parent::__construct($_name); 51 } 52 public function Apply(Request $_req) { 53 if ($_req->requestType == "請假" && $_req->num <= 5) { 54 echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批準。<br/>"; 55 } else { 56 if (isset($this->manager)) { 57 $this->manager->Apply($_req); 58 } 59 } 60 } 61 } 62 //總經理 63 class GeneralManager extends Manager { 64 public function __construct($_name) { 65 parent::__construct($_name); 66 } 67 public function Apply(Request $_req) { 68 if ($_req->requestType == "請假") { 69 echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批準。<br/>"; 70 } else if ($_req->requestType == "加薪" && $_req->num <= 500) { 71 echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}被批準。<br/>"; 72 } else if ($_req->requestType == "加薪" && $_req->num > 500) { 73 echo "{$this->name}:{$_req->requestContent} 數量{$_req->num}再說吧。<br/>"; 74 } 75 } 76 } 77 //--------------------客戶端---------------------- 78 $jingli = new CommonManager("李經理"); 79 $zongjian = new MajorDomo("郭總監"); 80 $zongjingli = new GeneralManager("孫總"); 81 //設置直接上級 82 $jingli->SetHeader($zongjian); 83 $zongjian->SetHeader($zongjingli); 84 //申請 85 $req1 = new Request(); 86 $req1->requestType = "請假"; 87 $req1->requestContent = "小菜請假!"; 88 $req1->num = 1; 89 $jingli->Apply($req1); 90 $req2 = new Request(); 91 $req2->requestType = "請假"; 92 $req2->requestContent = "小菜請假!"; 93 $req2->num = 4; 94 $jingli->Apply($req2); 95 $req3 = new Request(); 96 $req3->requestType = "加薪"; 97 $req3->requestContent = "小菜請求加薪!"; 98 $req3->num = 500; 99 $jingli->Apply($req3); 100 $req4 = new Request(); 101 $req4->requestType = "加薪"; 102 $req4->requestContent = "小菜請求加薪!"; 103 $req4->num = 1000; 104 $jingli->Apply($req4);

職責鏈模式 - 設計模式 - PHP版