本文實例講述了php設計模式之策略模式應用。分享給大家供大家參考,具體如下:
策略模式
定義:
策略模式定義一系列的算法,將每個算法封裝起來,并讓它們可以相互裝換。策略模式讓算法獨立于使用它的客戶而獨立變化。
角色分析:
應用場景:
代碼實現:
<?php/** * Created by PhpStorm. * Author: zhaorui * Date: 2019/2/27 * Time: 10:55 */header('Content-Type:text/html;charset=utf-8');// 抽象策略接口abstract class Strategy{ abstract function wayToSchool();}//具體策略角色class BikeStrategy extends Strategy{ function wayToSchool() { echo "騎自行車去上學".PHP_EOL; }}class BusStrategy extends Strategy{ function wayToSchool() { echo "乘公共汽車去上學".PHP_EOL; }}class TaxiStrategy extends Strategy{ function wayToSchool() { echo "坐出租去上學".PHP_EOL; }}// 環境角色class Context{ private $strategy; function getStrategy($strategyName){ try{ $strategyReflection = new ReflectionClass($strategyName); $this->strategy = $strategyReflection->newInstance(); }catch (ReflectionException $e){ $this->strategy = ""; } } function goToSchool(){ $this->strategy->wayToSchool(); }}// 測試$context = new Context();$context->getStrategy('BusStrategy');$context->goToSchool();
運行結果
乘公共汽車去上學
優點:
缺點:
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選