看板 PHP 關於我們 聯絡資訊
當敘述中越來越多 if else 或是充斥一堆 switch case時,debug 上是相當困難的。 要實作 unit test 也會增加不少困難度。 要解決這樣的問題會比較建議採用 Chain of Responsibility 模式(責任鏈模式) <?php abstract class Handler { protected $nextHandler; abstract function handle($number); public function __construct(Handler $handler = null) { if($handler !== null){ $this->addNextHandler($handler); } } public function addNextHandler(Handler $handler) { $this->nextHandler = $handler; } protected function handleNext($number) { if($this->nextHandler !== null){ $this->nextHandler->handle($number); } } } class lessThan extends Handler //負責處理小於的狀況 { function handle($number) { if($number < 5) { echo "$number < 5\n"; return; } $this->handleNext($number); } } class equal extends Handler //負責處理等於的狀況 { function handle($number) { if($number == 5) { echo "$number == 5\n"; return; } $this->handleNext($number); } } class greaterThan extends Handler //負責處理大於的狀況 { function handle($number) { if($number > 5) { echo "$number > 5\n"; return; } $this->handleNext($number); } } $handler = new lessThan(new equal(new greaterThan())); $handler->handle(1); //輸出 1 < 5 $handler->handle(5); //輸出 5 == 5 $handler->handle(6); //輸出 6 > 5 責任鍊顧名思義如果我能處理就接下來處理,如果不能處理就繼續往下丟, 直到處理完成為止。 這樣的好處是可以針對個別的 handler 做 unit test,另外當我要新增或是移除某個 handler 時也相當簡單不需要大幅度的變動整個 code。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.136.115 ※ 編輯: rickysu 來自: 220.130.136.115 (03/24 11:01)
dlikeayu:推CoR模式 03/26 08:58