策略模式:將一組特定行為與演算法封裝成類別,以適應特定情境。
電商網站依性別導向不同商品分類與廣告位。
<?php
namespace Baobab;
interface UserStrategy {
function showAd();
function showCategory();
}
class FemaleUserStrategy implements UserStrategy {
function showAd() { echo '2016新款女裝'; }
function showCategory() { echo '女裝'; }
}
class MaleUserStrategy implements UserStrategy {
function showAd() { echo 'Iphone6s plus'; }
function showCategory() { echo '電子產品'; }
}
class Page {
protected $strategy;
function Index() {
$this->strategy->showAd(); echo '<br/>';
$this->strategy->showCategory();
}
function setStrategy(UserStrategy $strategy) { $this->strategy = $strategy; }
}
$page = new Page();
if (isset($_GET['female'])) $strategy = new FemaleUserStrategy();
else $strategy = new MaleUserStrategy();
$page->setStrategy($strategy);
$page->Index();
透過策略模式實現 IoC(控制反轉)與依賴倒置,客戶端無需知道具體策略實作細節。