分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

PHP设计模式:策略模式

发布时间:2023-09-06 01:27责任编辑:蔡小小关键词:PHP
步骤1.定义策略接口

#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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved