PHP設計模式(3)—— 策略模式
阿新 • • 發佈:2018-12-01
基本概念
策略模式是一個非常常用,且非常有用的設計模式。
簡單的說,它是當你使用大量if else邏輯時的救星。
if else 就是一種判斷上下文的環境所作出的策略,如果你把if else寫死,那麼在複雜邏輯的時候你會發現程式碼超級長,而且最蛋疼的是,當你以後要新增策略時,再寫一個elseif?
萬一這個邏輯要修改20個地方呢?
策略模式就是來解決這個問題的。
舉一個場景,商城的首頁,男的進來看男性商品,女的進來看女性商品,不男不女…以此類推,各種條件下用不同策略展示不同商品。
實現
showStrategy.php 展示策略介面
interface showStrategy{
public function showCategory();
}
maleShowStrategy.php 男性使用者展示策略
class maleShowStrategy implements showStrategy { // 具體策略A
public function showCategory(){
echo '展示男性商品目錄';
}
}
femaleShowStrategy.php 女性使用者展示策略
class femaleShowStrategy implements showStrategy { // 具體策略B
public function showCategory(){
echo '展示女性商品目錄';
}
}
page.php 展示頁面
class Page{
private $_strategy;
public function __construct(Strategy $strategy) {
$this->_strategy = $strategy;
}
public function showPage() {
$this->_strategy->showCategory();
}
}
使用
if(isset($_GET['male'])){
$strategy = new maleShowStrategy();
}elseif(isset($_GET['female'])){
$strategy = new femaleShowStrategy();
}
//注意看這裡上下,Page類不再依賴一種具體的策略,而是隻需要繫結一個抽象的介面,這就是傳說中的控制反轉(IOC)。
$question = new Page($strategy);
$question->showPage();