PHP种的策略设计模式

策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。
策略模式除了实现分支逻辑的处理之外,还可以实现IoC,从而实现控制反转。

以一个电商系统为例,针对男性女性用户要各自跳转到不同的商品类目并且显示不同的内容。

//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 '电子产品';
    }

}

//FemaleStrategy.php 女性策略
<?php

namespace App\Strategy;

class FemaleStrategy implements UserStrategy
{
    function showAd()
    {
        echo 'lv';
    }

    function showCategory()
    {
        echo '化妆品';
    }
}

//Page.php 调用类
<?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();


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容