常用設計模式之PHP實現: 策略模式

業務部分參考自 https://blog.csdn.net/flitrue/article/details/52614599

策略模式 Strategy Pattern

定義一組算法, 將每個算法都封裝起來, 並且他們之間可以相互切換. 類似於"條條大路通羅馬".

Define a family of algorithms, encapsulate each one, and make them interchangeable.

假如有一個電商網站系統,針對男性女性用戶要各自跳轉到不同的商品類目,並且所有的廣告位展示不同的廣告。在傳統的代碼中,都是在系統中加入各種if else的判斷,硬編碼的方式。如果有一天增加了一種用戶,就需要改寫代碼。使用策略模式,如果新增加一種用戶類型,只需要增加一種策略就可以。其他所有的地方只需要使用不同的策略就可以。

首先聲明策略的接口文件,約定了策略的包含的行爲。然後,定義各個具體的策略實現類。

//接口
interface UserStrategy{
    function showAd();
    function showCategory();
}

//實現類
class FemaleUser implements UserStrategy{
    function showAd() {
        echo 'This is female showAd';
    }
    function showCategory() {
        echo 'This is female showCategory';
    }
}
class MaleUser implements UserStrategy{
    function showAd() {
        echo 'This is male showAd';
    }
    function showCategory() {
        echo 'This is male showCategory';
    }
}

//業務邏輯類
class Page{
    /** @var \UserStrategy */
    protected $strategy;
    public function __construct(\UserStrategy $strategy){
        $this->strategy = $strategy;
    }
    public function index(){
        echo 'AD:';
        $this->strategy->showAd();
        echo PHP_EOL;
        echo 'Category:';
        echo $this->strategy->showCategory();
    }

}

//命令行下直接隨機測試
if(rand(1,2) == 1){
    $strategy = new MaleUser();
}
else{
    $strategy = new FemaleUser();
}
$page = new Page($strategy);
$page->index();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章