zoukankan      html  css  js  c++  java
  • php设计模式 策略模式

    策略模式:

    将一组特定的行为和算法封装成类,以适应某些特定的上下文环境;

    实际应用举例,假如一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有广告位展示不同的广告。

    UserStrategy.php

    <?php
    namespace Baobab;
    
    interface UserStrategy{
        function showAd();
        function showCategory();
    }
    ?>

    FemaleUserStrategy.php

    <?php
    namespace Baobab;
    
    class FemaleUserStrategy implements UserStrategy{
        function showAd(){
            echo '2016新款女装';
        }
        function showCategory(){
            echo '女装';
        }
    }
    
    ?>

    MaleUserStrategy.php

    <?php
    namespace Baobab;
    
    class MaleUserStrategy implements UserStrategy{
        function showAd(){
            echo 'Iphone6s plus';
        }
        function showCategory(){
            echo '电子产品';
        }
    }
    
    ?>

    Page.php

    namespace Baobab;

    class
    Page{ protected $strategy; function Index(){ $this->strategy->showAd(); echo '<br/>'; $this->strategy->showCategory(); } function setStrategy(BaobabUserStrategy $strategy){ $this->strategy = $strategy; } }

    index.php

    $page = new BaobabPage();
    if (isset($_GET['female'])){
        $strategy = new BaobabFemaleUserStrategy();
    }else{
        $strategy = new BaobabMaleUserStrategy();
    }
    $page->setStrategy($strategy);
    $page->Index();

    使用策略模式可实现Ioc,依赖倒置、控制反转

  • 相关阅读:
    读本地json的方法
    告诉你如何应对HR索要薪资证明!
    函数声明与函数表达式
    原型的动态性
    工作实际需求andjs进阶图书
    表单元素操作,button,点击下载按钮实现-长知识
    grunt注意要点
    重新认识块级元素--DIV
    GO语言学习:变量间赋值
    GO语言学习:单通道
  • 原文地址:https://www.cnblogs.com/tianxintian22/p/5228370.html
Copyright © 2011-2022 走看看