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

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();

本文由 admin 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论