本文实例讲述了PHP单例模式模拟Java Bean实现方法。分享给大家供大家参考,具体如下:
问题:
根据如下杨辉三角形
实现一个get_value($row,$col)
方法:
(前一个由于代码是手机编辑的,很乱,重新发下)只是为了实现这个方法,很简单,几行代码就能实现,但如果行和列的值稍微大点,你就发现,运行时间很长。所以就这次的题做了个稍微复杂点的例子,说明下单例模式的使用、static的使用、模拟Java Bean、static的使用、递归函数案例等。
/** * author Winter * 2016-11-22 * PHP的单例模式 * 模拟Java Bean * Class Php_bean */ class Php_bean{ private static $_instance = null; private function __construct(){} private $hit = 0;//命中次数 private $array = array();//缓存 private $itratorCount = 0;//迭代次数 public function add_itratorCount(){ $this->itratorCount ++; } public function get_itratorCount(){ return $this->itratorCount; } public function set_cache($row,$col,$value){ $this->array[$row."_".$col] = $value; } public function get_cache($row,$col){ if(isset($this->array[$row."_".$col])){ return $this->array[$row."_".$col]; }else{ return false; } } public function add_hit(){ $this->hit ++; } public function get_hit(){ return $this->hit; } public static function instance(){ if(self::$_instance instanceof self) return self::$_instance; self::$_instance = new self; return self::$_instance; } } /** * @param $row 行 * @param $col 列 * @return int */ function get_value($row,$col){ $php_bean = Php_bean::instance(); $php_bean->add_itratorCount(); if($col > $row) return 0; if($row <=0) return 0; if($col == $row) return 1; if($row == 1) return 1; if($col == 1) return 1; $pre = $php_bean->get_cache($row-1,$col-1); $next = $php_bean->get_cache($row-1,$col-0); if($pre === false){ $pre = get_value($row-1,$col-1); $php_bean->set_cache($row-1,$col-1,$pre); }else{ $php_bean->add_hit(); } if($next === false){ $next = get_value($row-1,$col-0); $php_bean->set_cache($row-1,$col-0,$next); }else{ $php_bean->add_hit(); } $value = $pre + $next; return $value; } $v = get_value(6,6); var_dump($v); $php_bean_obj = Php_bean::instance(); echo "hit:".$php_bean_obj->get_hit()."<br/>"; echo "itratorCount:".$php_bean_obj->get_itratorCount()."<br/>";
运行结果:
int(1) hit:0
itratorCount:1
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 何耀珊.2006-收获【华纳】【WAV+CUE】
- 梁汉文1994-壹精选[华星][WAV+CUE]
- 洪荣宏1981-歹路不可行·相思雨(飞跃复刻版)[光美][WAV+CUE]
- 旅行团2015-10Day’s[来福胶泥][WAV+CUE]
- 龙千玉.2011-卡将哟【豪记】【WAV+CUE】
- 蔣志光.1993-多情多寂寞(国专)【BMG】【WAV+CUE】
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]
- 周冰倩1995《沧桑情歌》JVC日本录制[WAV+CUE]
- 辛禄乐队.2024-热烈的少年【星辰】【FLAC分轨】
- 成龙.1996-龙的心【滚石】【WAV+CUE】