PHP种的策略设计模式

2017-04-18  本文已影响12人  zshanjun

策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。
策略模式除了实现分支逻辑的处理之外,还可以实现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();


上一篇 下一篇

猜你喜欢

热点阅读