PHP设计模式:策略模式
步骤1.定义策略接口
#UserStrategy.php用户策略<?phpnamespacecelvmoshi;/**用户策略接口*InterfaceUserStategy*@packagecelvmoshi*/interfaceUserStrategy{//显示广告publicfunctionshowAd();//显示分类publicfunctionshowCategory();}
步骤2.实现策略业务
#FemaleStrategy.php女性用户策略<?phpnamespacecelvmoshi;/**女性用户策略*ClassFemaleStrayegy*@packagecelvmoshi*/classFemaleStrategyimplementsUserStrategy{publicfunctionshowAd(){echo"2017新潮女装\r\n";}publicfunctionshowCategory(){echo"服装\r\n";}}
继续添加策略
#MaleStrategy.php男性用户策略<?phpnamespacecelvmoshi;/**男性用户策略*ClassMaleStrayegy*@packagecelvmoshi*/classMaleStrategyimplementsUserStrategy{//显示广告publicfunctionshowAd(){echo"新款宝马X6\r\n";}//显示分类publicfunctionshowCategory(){echo"小汽车\r\n";}}
步骤3.在实际业务场景中运用策略
本实例的业务场景为:根据男女、性用户自动区分广告及分类
#index.php默认业务访问入口<?phpdefine('ROOT',__DIR__.'/');//实现自动加载spl_autoload_register('autoload');functionautoload($className){$arr=explode('\\',$className);require_onceROOT.ucfirst($arr[1]).'.php';}classPage{protected$strategy;//显示策略publicfunctionindex(){echo"显示广告:";$this->strategy->showAd();echo"<hr>";echo"显示分类:";$this->strategy->showCategory();}//设置显示策略publicfunctionsetStrategy(celvmoshi\UserStrategy$strategy)//(约定接口类型){$this->strategy=$strategy;}}$page=newPage();if(isset($_GET['female'])){$userStrategy=newcelvmoshi\FemaleStrategy();}elseif(isset($_GET['male'])){$userStrategy=newcelvmoshi\MaleStrategy();}else{return;}$page->setStrategy($userStrategy);$page->index();
至此已大功告成!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。