温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP设计模式:策略模式

发布时间:2020-06-07 17:27:53 来源:网络 阅读:1844 作者:hgditren 栏目:web开发

步骤1.定义策略接口

#UserStrategy.php 用户策略 <?php namespace celvmoshi; /**用户策略接口  * Interface UserStategy  * @package celvmoshi  */ interface UserStrategy {     //显示广告     public function showAd();     //显示分类     public function showCategory(); }


步骤2.实现策略业务

#FemaleStrategy.php 女性用户策略 <?php namespace celvmoshi; /**女性用户策略  * Class FemaleStrayegy  * @package celvmoshi  */ class FemaleStrategy implements UserStrategy {     public function showAd()     {         echo "2017 新潮女装\r\n";     }     public function showCategory()     {         echo "服装\r\n";     } }


继续添加策略

#MaleStrategy.php 男性用户策略 <?php namespace celvmoshi; /**男性用户策略  * Class MaleStrayegy  * @package celvmoshi  */ class MaleStrategy implements UserStrategy {     //显示广告     public function showAd()     {         echo "新款宝马X6\r\n";     }     //显示分类     public function showCategory()     {         echo "小汽车\r\n";     } }



步骤3.在实际业务场景中运用策略

本实例的业务场景为:根据男女、性用户自动区分广告及分类

#index.php 默认业务访问入口 <?php define('ROOT', __DIR__ . '/'); //实现自动加载 spl_autoload_register('autoload'); function autoload($className) {     $arr = explode('\\', $className);     require_once ROOT . ucfirst($arr[1]) . '.php'; } class Page {     protected $strategy;//显示策略     public function index()     {         echo "显示广告:";         $this->strategy->showAd();         echo "<hr>";         echo "显示分类:";         $this->strategy->showCategory();     }     //设置显示策略     public function setStrategy(celvmoshi\UserStrategy $strategy)//(约定接口类型)     {         $this->strategy = $strategy;     } } $page = new Page(); if (isset($_GET['female'])) {     $userStrategy = new celvmoshi\FemaleStrategy(); } else if (isset($_GET['male'])) {     $userStrategy = new celvmoshi\MaleStrategy(); } else {     return; } $page->setStrategy($userStrategy); $page->index();



至此已大功告成!


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI