#UserStrategy.php 用户策略<?phpnamespace celvmoshi;/**用户策略接口 * Interface UserStategy * @package celvmoshi */interface UserStrategy{ //显示广告 public function showAd(); //显示分类 public function showCategory();}
步骤2.实现策略业务
#FemaleStrategy.php 女性用户策略<?phpnamespace celvmoshi;/**女性用户策略 * Class FemaleStrayegy * @package celvmoshi */class FemaleStrategy implements UserStrategy{ public function showAd() { echo "2017 新潮女装\r\n"; } public function showCategory() { echo "服装\r\n"; }}
继续添加策略
#MaleStrategy.php 男性用户策略<?phpnamespace 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 默认业务访问入口<?phpdefine('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();
至此已大功告成!
PHP设计模式:策略模式
原文地址:http://blog.51cto.com/phpme/2045866