本文实例讲述了php设计模式之策略模式应用。分享给大家供大家参考,具体如下:
策略模式
定义:
策略模式定义一系列的算法,将每个算法封装起来,并让它们可以相互装换。策略模式让算法独立于使用它的客户而独立变化。
角色分析:
应用场景:
代码实现:
<?php /** * created by phpstorm. * author: zhaorui * date: 2019/2/27 * time: 10:55 */ header('content-type:text/html;charset=utf-8'); // 抽象策略接口 abstract class strategy{ abstract function waytoschool(); } //具体策略角色 class bikestrategy extends strategy{ function waytoschool() { echo "骑自行车去上学".php_eol; } } class busstrategy extends strategy{ function waytoschool() { echo "乘公共汽车去上学".php_eol; } } class taxistrategy extends strategy{ function waytoschool() { echo "坐出租去上学".php_eol; } } // 环境角色 class context{ private $strategy; function getstrategy($strategyname){ try{ $strategyreflection = new reflectionclass($strategyname); $this->strategy = $strategyreflection->newinstance(); }catch (reflectionexception $e){ $this->strategy = ""; } } function gotoschool(){ $this->strategy->waytoschool(); } } // 测试 $context = new context(); $context->getstrategy('busstrategy'); $context->gotoschool();
运行结果
乘公共汽车去上学
优点:
缺点:
更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
如何去设计前端框架能力?星巴克消息开放项目从0到1,从点到面的思考
PHP制作日历,实现在1970年到2020年之间的任何一个月份的输出。上半部分
网友评论