PHP设计模式:策略模式
更新:HHH   时间:2023-1-7


步骤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();



至此已大功告成!


返回web开发教程...