ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 7-1 策略模式的实现和使用 ### 第一步:创建策略的接口文件 文件约定了策略拥有哪些行为。 *D:\wamp\www\demo\oop\framework\Think\UserStrategy.php* ~~~ <?php namespace Think; // 定义一个用户的策略接口 interface UserStrategy { function showAd(); function showCategory(); } ~~~ ### 第二步:策略实现 接口定义完毕,我们就应该定义具体的策略实现。 分别定义了 女性用户的策略,男性用户的策略 *D:\wamp\www\demo\oop\framework\Think\FemaleUserStrategy.php* ~~~ <?php namespace Think; class FemaleUserStrategy implements UserStrategy { function showAd() { echo "2017新款女装"; } function showCategory() { echo "女装目录"; } } ~~~ *D:\wamp\www\demo\oop\framework\Think\MaleUserStrategy.php* ~~~ <?php namespace Think; class MaleUserStrategy implements UserStrategy { function showAd() { echo "电子产品"; } function showCategory() { echo "3C配件目录"; } } ~~~ ### 第三步:使用策略前 *D:\wamp\www\demo\oop\framework\index.php* 传统的方法需要写这些条件分支语句,才能实现需求,但是不足之处在于一旦需要增加条件,那么所有使用到这些分支的地方都需要修改。 ~~~ <?php // 入口文件 define('BASEDIR', __DIR__); include BASEDIR . '/Think/Loder.php'; spl_autoload_register('\\Think\\Loder::autoload'); class Page { function index() { // 首页显示 if ($_GET['m'] == "female") { # code... } elseif ($_GET['m'] == "male") { # code... } else { // } } } $page = new Page(); $page->index(); ~~~ ### 第四步:使用策略模式 *D:\wamp\www\demo\oop\framework\index.php* ~~~ // 设置策略的方法 function setStrategy(Think\UserStrategy $strategy) { $this->strategy = $strategy; } ~~~ 给 `Page` 类添加一个 设置策略的 方法,该方法 约定了接口的类型 为:UserStrategy。 然后,我们就可以根据条件 来实例化策略,并把对象传递给 Page类 ~~~ // 根据条件实例化对应的策略 if (isset($_GET['m']) && $_GET['m'] == 'female') { $strategy = new Think\FemaleUserStrategy(); } else { $strategy = new Think\MaleUserStrategy(); } // 把策略的对象,传递到页面的对象中 $page->setStrategy($strategy); ~~~ 最后,在Page类的 index() 方法里,不使用任何的分支结构,直接调用策略对象中的实现方法即可! ~~~ function index() { // 这里不需要使用分支结构,直接调用策略的对象的实现方法 $this->strategy->showAd(); $this->strategy->showCategory(); } ~~~ *D:\wamp\www\demo\oop\framework\index.php* ~~~ <?php // 入口文件 define('BASEDIR', __DIR__); include BASEDIR . '/Think/Loder.php'; spl_autoload_register('\\Think\\Loder::autoload'); class Page { protected $strategy; function index() { // 这里不需要使用分支结构,直接调用策略的对象的实现方法 $this->strategy->showAd(); $this->strategy->showCategory(); } // 设置策略的方法 function setStrategy(Think\UserStrategy $strategy) { $this->strategy = $strategy; } } $page = new Page(); // 根据条件实例化对应的策略 if (isset($_GET['m']) && $_GET['m'] == 'female') { $strategy = new Think\FemaleUserStrategy(); } else { $strategy = new Think\MaleUserStrategy(); } // 把策略的对象,传递到页面的对象中 $page->setStrategy($strategy); $page->index(); ~~~