PHP 设计模式 笔记与总结(8)策略模式

① 策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境,这种模式就是策略模式。

② 实际应用举例,假如一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有广告位展示不同的广告。

 

在 Common 目录下新建 UserStrategy.php,定义接口:

<?php
namespace Common;

//定义策略接口
interface UserStrategy{
    //显示广告
    function showAd();
    //展示类目
    function showCategory();
}

在 Common 目录下新建 FemaleUserStrategy.php ,女性用户的策略实现:

<?php
/*
 * 女性用户的策略实现
 */
namespace Common;
use Common\UserStrategy;

class FemaleUserStrategy implements UserStrategy{
   
    function showAd(){
        echo '2015春夏新款女装';
    }
   
    function showCategory(){
        echo '女装';
    }
} 

 

在 Common 目录下新建 MaleUserStrategy.php ,男性用户的策略实现:  

<?php
/*
 * 男性用户的策略实现
 */
namespace Common;
use Common\UserStrategy;

class MaleUserStrategy implements UserStrategy{
   
    function showAd(){
        echo 'Apple Watch';
    }
   
    function showCategory(){
        echo '电子产品';
    }
} 

 

入口文件 index.php:

<?php
define('BASEDIR',__DIR__); //定义根目录常量
include BASEDIR.'/Common/Loader.php';
spl_autoload_register('\\Common\\Loader::autoload');

class Page{
    
    protected $strategy;
            
    function index(){
        echo 'AD:';
        $this->strategy->showAd();
        echo '<br>Category:';
        $this->strategy->showCategory();
    }
    
    //用于外部设置策略
    function setStrategy(\Common\UserStrategy $strategy){
        $this->strategy = $strategy;
    }
}

$page = new Page();
if(isset($_GET['female'])){
    $strategy = new \Common\FemaleUserStrategy();
}else{
    $strategy = new \Common\MaleUserStrategy();
}
$page->setStrategy($strategy);
$page->index();

访问 http://127.0.0.17/php/design/psr0/index.php?female

输出:

AD:2015春夏新款女装
Category:女装

访问 http://127.0.0.17/php/design/psr0/index.php

输出:

AD:Apple Watch
Category:电子产品


 

【策略模式的控制反转】

③ 使用策略模式可以实现 Ioc,依赖倒置、控制反转

在上例中 Page 类 依赖于 MaleUserStrategy 类和 FemaleUserStrategy 类。在 Page 类中不需要实现这两个类,在执行的过程中,才将这个关系进行绑定。

 

==

如果两个类是互相依赖的关系,那么它们之间就是一个紧耦合的设计,不利于替换其中某一个环节;而策略模式使用依赖倒置以后,就可以很方便地替换其中某一个类。

posted @ 2015-04-11 13:44  nemo20  阅读(246)  评论(0编辑  收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计