php設計模式 策略模式,php設計模式_PHP教程

來源:互聯網
上載者:User

php設計模式 策略模式,php設計模式


策略模式:

將一組特定的行為和演算法封裝成類,以適應某些特定的上下文環境;

實際應用舉例,假如一個電商網站系統,針對男性女性使用者要各自跳轉到不同的商品類目,並且所有廣告位展示不同的廣告。

UserStrategy.php

phpnamespace Baobab;interface UserStrategy{    function showAd();    function showCategory();}?>

FemaleUserStrategy.php

phpnamespace Baobab;class FemaleUserStrategy implements UserStrategy{    function showAd(){        echo '2016新款女裝';    }    function showCategory(){        echo '女裝';    }}?>

MaleUserStrategy.php

phpnamespace 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,依賴倒置、控制反轉

http://www.bkjia.com/PHPjc/1104059.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104059.htmlTechArticlephp設計模式 策略模式,php設計模式 策略模式: 將一組特定的行為和演算法封裝成類,以適應某些特定的上下文環境; 實際應用舉例,假如一...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.