策略模式:
將一組特定的行為和算法封裝成類,以適應某些特定的上下文環境;
實際應用舉例,假如一個電商網站系統,針對男性女性用戶要各自跳轉到不同的商品類目,並且所有廣告位展示不同的廣告。
UserStrategy.php
<?php
namespace Baobab;
interface UserStrategy{
function showAd();
function showCategory();
}
?>
FemaleUserStrategy.php
<?php
namespace Baobab;
class FemaleUserStrategy implements UserStrategy{
function showAd(){
echo '2016新款女裝';
}
function showCategory(){
echo '女裝';
}
}
?>
MaleUserStrategy.php
<?php
namespace 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 '<br/>';
$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,依賴倒置、控制反轉