欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php设计模式 策略模式,php设计模式_PHP教程

程序员文章站 2022-05-10 17:33:43
...

php设计模式 策略模式,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 '电子产品';
    }
}

?>

index.php

class Page{
     protected $strategy;
     function Index(){
         $this->strategy->showAd();
         echo '
'; $this->strategy->showCategory(); } function setStrategy(Baobab\UserStrategy $strategy){ $this->strategy = $strategy; } } $page = new Page(); if (isset($_GET['female'])){ $strategy = new Baobab\FemaleUserStrategy(); }else{ $strategy = new Baobab\MaleUserStrategy(); } $page->setStrategy($strategy); $page->Index();

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104059.htmlTechArticlephp设计模式 策略模式,php设计模式 策略模式: 将一组特定的行为和算法封装成类,以适应某些特定的上下文环境; 实际应用举例,假如一...