美文网首页
PHP种的策略设计模式

PHP种的策略设计模式

作者: zshanjun | 来源:发表于2017-04-18 19:36 被阅读12次

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


相关文章

  • PHP设计模式之策略模式

    PHP设计模式之策略模式

  • PHP设计模式之策略模式

    PHP设计模式之策略模式

  • 策略模式和工厂模式在促销系统下的应用

    策略模式和工厂模式在促销系统下的应用 标签: 设计模式 策略模式 工厂模式 促销系统 php 设计模式为我们提供了...

  • PHP种的策略设计模式

    策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。策略模式除了实现分支逻...

  • PHP设计模式(三)-策略模式

    layout: posttitle: "PHP设计模式(三)-策略模式"date: 2016-06-06 10:3...

  • PHP设计模式

    以下列出的为常见的PHP设计模式 策略模式 在策略模式(Strategy Pattern)中,一个类的行为或其算法...

  • php设计模式

    1. 设计模式原则 2.php使用的设计模式(23种)

  • PHP设计模式-策略模式

    定义 策略模式 定义了算法族,并分别封装起来,让它们之间可以相互替换,让算法的变化独立于使用算法的客户 优点 策略...

  • PHP设计模式:策略模式

    前言 策略模式的应用非常的多,尤其在商城中更是经常会被用到,打个比方,我们生活中经常遇到的优惠,优惠就有很多的策略...

  • PHP设计模式-策略模式

    策略模式 用途 分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类...

网友评论

      本文标题:PHP种的策略设计模式

      本文链接:https://www.haomeiwen.com/subject/gteqzttx.html