文章主要介紹了PHP單例模式模擬Java Bean實(shí)現(xiàn)方法,涉及php面向?qū)ο蟪绦蛟O(shè)計(jì)相關(guān)操作技巧,需要的朋友可以參考下。
實(shí)例講述了PHP單例模式模擬Java Bean實(shí)現(xiàn)方法,具體如下:
問(wèn)題:
根據(jù)如下楊輝三角形

實(shí)現(xiàn)一個(gè)get_value($row,$col)方法:
(前一個(gè)由于代碼是手機(jī)編輯的,很亂,重新發(fā)下)只是為了實(shí)現(xiàn)這個(gè)方法,很簡(jiǎn)單,幾行代碼就能實(shí)現(xiàn),但如果行和列的值稍微大點(diǎn),你就發(fā)現(xiàn),運(yùn)行時(shí)間很長(zhǎng)。所以就這次的題做了個(gè)稍微復(fù)雜點(diǎn)的例子,說(shuō)明下單例模式的使用、static的使用、模擬Java Bean、static的使用、遞歸函數(shù)案例等。?
/*** author Winter* 2016-11-22* PHP的單例模式* 模擬Java Bean* Class Php_bean*/classPhp_bean{privatestatic$_instance= null;privatefunction__construct(){}private$hit= 0;//命中次數(shù)private$array=array();//緩存private$itratorCount= 0;//迭代次數(shù)publicfunctionadd_itratorCount(){$this->itratorCount ++;}publicfunctionget_itratorCount(){return$this->itratorCount;}publicfunctionset_cache($row,$col,$value){$this->array[$row."_".$col] =$value;}publicfunctionget_cache($row,$col){if(isset($this->array[$row."_".$col])){return$this->array[$row."_".$col];}else{returnfalse;}}publicfunctionadd_hit(){$this->hit ++;}publicfunctionget_hit(){return$this->hit;}publicstaticfunctioninstance(){if(self::$_instanceinstanceofself)returnself::$_instance;self::$_instance=newself;returnself::$_instance;}}/*** @param $row 行* @param $col 列* @return int*/functionget_value($row,$col){$php_bean= Php_bean::instance();$php_bean->add_itratorCount();if($col>$row)return0;if($row<=0)return0;if($col==$row)return1;if($row== 1)return1;if($col== 1)return1;$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/>";
運(yùn)行結(jié)果:
int(1) hit:0
itratorCount:1
希望PHP單例模式模擬Java Bean實(shí)現(xiàn)方法示例詳解所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- PHP圖像處理繪圖、水印、驗(yàn)證碼、圖像壓縮技術(shù)實(shí)例總
- PHP實(shí)現(xiàn)高清晰度無(wú)損圖片壓縮功能的代碼
- 用PHP處理png圖片白色背景色改為透明色的實(shí)例代碼
- 關(guān)于PHP往mysql數(shù)據(jù)庫(kù)中批量插入數(shù)據(jù)實(shí)例教程
- Php兩點(diǎn)地理坐標(biāo)距離的計(jì)算方法和具體代碼
- PHP獲取HTTP body內(nèi)容的方法
- PHP面向?qū)ο蟪绦蛟O(shè)計(jì)中獲取對(duì)象屬性的3種方法實(shí)例分析
- php5.5新增的yield關(guān)鍵字功能與相關(guān)使用技巧
- Windows7下IIS+php配置教程詳細(xì)介紹
- PHP序列化的四種實(shí)現(xiàn)方法與橫向?qū)Ρ冉坛?/a>
分享到:
投訴收藏














