PHP 策略模式--按性别显示商品推荐

4个PHP文件
index.php 主入口
app\UserStrategy.php 接口文件
app\FemaleUserStrategy.php 策略文件
app\MaleUserStrategy.php 策略文件

require 'App\UserStrategy.php';
require 'App\FemaleUserStrategy.php';
require 'App\MaleUserStrategy.php';
use App\UserStrategy;
use App\FemaleUserStrategy;
use App\MaleUserStrategy;

class Page{
    protected $strategy;
    function index(){
        $this->strategy->showAd();
        echo "<br/>";
        $this->strategy->showCategory();
    }
    function setStrategy(UserStrategy $strategy){
        $this->strategy=$strategy;
    }
}

$page=new Page;
if(isset($_GET['female'])){
    $strategy=new FemaleUserStrategy();
}else{
    $strategy=new MaleUserStrategy();
}
$page->setStrategy($strategy);
$page->index();
namespace App;
interface UserStrategy {
    function showAd();
    function showCategory();
} 
namespace App;
//策略模式-男
class MaleUserStrategy implements UserStrategy  {
    function showAd()    {
        echo "IPhone6";
    }
    function showCategory()    {
        echo "电子产品";
    }
} 
namespace App;
//策略模式-女
class FemaleUserStrategy implements UserStrategy {
    function showAd()    {
        echo "2014新款女装";
    }
    function showCategory()    {
        echo "女装";
    }
} 
可以看出page类与多个策略类是可以任意切换的,并不相互依赖,非耦合;策略模式实现了依赖倒置,解决了该类耦合问题
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容