php設計模式 策略模式,php設計模式
策略模式:
將一組特定的行為和演算法封裝成類,以適應某些特定的上下文環境;
實際應用舉例,假如一個電商網站系統,針對男性女性使用者要各自跳轉到不同的商品類目,並且所有廣告位展示不同的廣告。
UserStrategy.php
phpnamespace Baobab;interface UserStrategy{ function showAd(); function showCategory();}?>
FemaleUserStrategy.php
phpnamespace Baobab;class FemaleUserStrategy implements UserStrategy{ function showAd(){ echo '2016新款女裝'; } function showCategory(){ echo '女裝'; }}?>
MaleUserStrategy.php
phpnamespace Baobab;class MaleUserStrategy implements UserStrategy{ function showAd(){ echo 'Iphone6s plus'; } function showCategory(){ echo '電子產品'; }}?>
index.php
class Page{ protected $strategy; function Index(){ $this->strategy->showAd(); echo '
'; $this->strategy->showCategory(); } function setStrategy(Baobab\UserStrategy $strategy){ $this->strategy = $strategy; }}$page = new Page();if (isset($_GET['female'])){ $strategy = new Baobab\FemaleUserStrategy();}else{ $strategy = new Baobab\MaleUserStrategy();}$page->setStrategy($strategy);$page->Index();
使用原則模式可實現Ioc,依賴倒置、控制反轉
http://www.bkjia.com/PHPjc/1104059.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104059.htmlTechArticlephp設計模式 策略模式,php設計模式 策略模式: 將一組特定的行為和演算法封裝成類,以適應某些特定的上下文環境; 實際應用舉例,假如一...