PHP设计模式:策略模式
2017-11-30 00:00
531 查看
步骤1.定义策略接口
步骤2.实现策略业务
继续添加策略
步骤3.在实际业务场景中运用策略
本实例的业务场景为:根据男女、性用户自动区分广告及分类
至此已大功告成!
#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();
至此已大功告成!
相关文章推荐
- [置顶] php设计模式之策略模式
- php常用设计模式(策略模式/单例模式/工厂模式)
- PHP设计模式-策略模式
- php设计模式——策略模式
- PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)
- PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)
- php设计模式之策略模式
- PHP设计模式系列 - 策略模式
- php设计模式二之策略模式
- 学习php设计模式 php实现策略模式(strategy)
- PHP设计模式之策略模式
- PHP设计模式——策略模式
- PHP设计模式——策略模式
- 设计模式php实例:策略模式
- php设计模式 Strategy(策略模式)
- 初识PHP设计模式--策略模式
- PHP设计模式之——策略模式
- php设计模式之策略模式
- PHP:设计模式之策略模式
- php设计模式之策略模式