2019-04-03 15:35:42 1598浏览
本篇文章扣丁学堂PHP培训小编给喜欢PHP开发技术的读者们分享一下PHP单例模式模拟Java Bean实现方法,文中有对PHP面向对象程序设计相关操作技巧的简单介绍,对PHP开发技术感兴趣的小伙伴随小编来看一下吧。
问题:根据如下杨辉三角形
实现一个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培训官网、微信等平台,扣丁学堂IT职业在线学习教育有专业的PHP讲师为您指导,此外扣丁学堂老师精心推出的PHP视频教程定能让你快速掌握PHP从入门到精通开发实战技能。扣丁学堂PHP技术交流群:374332265。
【关注微信公众号获取更多学习资料】 【扫码进入HTML5进阶免费公开课】