php设计模式之策略模式


策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。
女性用户类

class FemaleUserStrategy implements UserStrategy
{
function showAd()
{
    // TODO: Implement showAd() method.
      echo "2020新款女装";
}
function showCategory()
{
    // TODO: Implement showCategory() method.
    echo "女装";
}
}

男性用户类

class MaleUserStrategy implements  UserStrategy
{
 function showAd()
 {
     // TODO: Implement showAd() method
     echo "Iphone 6";
 }
 function showCategory()
 {
     // TODO: Implement showCategory() method.
     echo "数码产品";
 }
}

场景

class Page{
    protected $strategy;
    function index(){
        echo 'AD:';
      $this->strategy->showAd();
      echo "<br>";
      echo "类目:";
      $this->strategy->showCategory();
    }
    function setStrategy(\IMooc\UserStrategy $strategy){
        $this->strategy=$strategy;
    }
}
$page=new Page;
if(isset($_GET['female'])){
    $strategy=new \IMooc\FemaleUserStrategy();
}else{
    $strategy=new \IMooc\MaleUserStrategy();
}
 $page->setStrategy($strategy);
$page->index();

文章作者: Jacky
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jacky !
  目录