1. 程式人生 > >PHP設計模式:策略模式

PHP設計模式:策略模式

php interface 設計模式 策略模式

步驟1.定義策略接口

#UserStrategy.php 用戶策略

<?php

namespace celvmoshi;

/**用戶策略接口
 * Interface UserStategy
 * @package celvmoshi
 */
interface UserStrategy
{
    //顯示廣告
    public function showAd();

    //顯示分類
    public function showCategory();

}


步驟2.實現策略業務

#FemaleStrategy.php 女性用戶策略
<?php
namespace celvmoshi;

/**女性用戶策略
 * Class FemaleStrayegy
 * @package celvmoshi
 */
class FemaleStrategy implements UserStrategy
{
    public function showAd()
    {
        echo "2017 新潮女裝\r\n";
    }

    public function showCategory()
    {
        echo "服裝\r\n";
    }
}


繼續添加策略

#MaleStrategy.php 男性用戶策略

<?php
namespace celvmoshi;

/**男性用戶策略
 * Class MaleStrayegy
 * @package celvmoshi
 */

class MaleStrategy implements UserStrategy
{
    //顯示廣告
    public function showAd()
    {
        echo "新款寶馬X6\r\n";
    }

    //顯示分類
    public function showCategory()
    {
        echo "小汽車\r\n";
    }
}



步驟3.在實際業務場景中運用策略

本實例的業務場景為:根據男女、性用戶自動區分廣告及分類

#index.php 默認業務訪問入口

<?php
define('ROOT', __DIR__ . '/');

//實現自動加載
spl_autoload_register('autoload');
function autoload($className)
{
    $arr = explode('\\', $className);
    require_once ROOT . ucfirst($arr[1]) . '.php';
}

class Page
{
    protected $strategy;//顯示策略

    public function index()
    {
        echo "顯示廣告:";
        $this->strategy->showAd();

        echo "<hr>";

        echo "顯示分類:";
        $this->strategy->showCategory();


    }

    //設置顯示策略
    public function setStrategy(celvmoshi\UserStrategy $strategy)//(約定接口類型)
    {
        $this->strategy = $strategy;
    }
}

$page = new Page();
if (isset($_GET['female'])) {
    $userStrategy = new celvmoshi\FemaleStrategy();
} else if (isset($_GET['male'])) {
    $userStrategy = new celvmoshi\MaleStrategy();
} else {
    return;
}

$page->setStrategy($userStrategy);
$page->index();



至此已大功告成!


PHP設計模式:策略模式