策略模式,將一組特定的行為和算法封裝成類,以適應(yīng)某些特定的上下文環(huán)境,這種模式就是策略模式。
策略模式除了實(shí)現(xiàn)分支邏輯的處理之外,還可以實(shí)現(xiàn)IoC,從而實(shí)現(xiàn)控制反轉(zhuǎn)。
以一個(gè)電商系統(tǒng)為例,針對(duì)男性女性用戶要各自跳轉(zhuǎn)到不同的商品類目并且顯示不同的內(nèi)容。
//UserStrategy.php
<?php
namespace App\Strategy;
interface UserStrategy
{
function showAd();
function showCategory();
}
//MaleStrategy.php 男性策略
<?php
namespace App\Strategy;
class MaleStrategy implements UserStrategy
{
function showAd()
{
echo 'iphone 8';
}
function showCategory()
{
echo '電子產(chǎn)品';
}
}
//FemaleStrategy.php 女性策略
<?php
namespace App\Strategy;
class FemaleStrategy implements UserStrategy
{
function showAd()
{
echo 'lv';
}
function showCategory()
{
echo '化妝品';
}
}
//Page.php 調(diào)用類
<?php
namespace App;
use App\Strategy\UserStrategy;
class Page
{
protected $strategy;
public function index()
{
$this->strategy->showAd();
$this->strategy->showCategory();
}
public function setStrategy(UserStrategy $strategy)
{
$this->strategy = $strategy;
}
}
//使用示例
<?php
use App\Page;
use App\Strategy\FemaleStrategy;
use App\Strategy\MaleStrategy;
$page = new Page();
if (isset($_GET['male'])) {
$strategy = new MaleStrategy();
} else {
$strategy = new FemaleStrategy();
}
$page->setStrategy($strategy);
$page->index();