PHP設(shè)計模式之迭代器模式
來源:易賢網(wǎng) 閱讀:645 次 日期:2016-08-16 16:21:35
溫馨提示:易賢網(wǎng)小編為您整理了“PHP設(shè)計模式之迭代器模式”,方便廣大網(wǎng)友查閱!

在不需要了解內(nèi)部實現(xiàn)的前提下,遍歷一個聚合對象的內(nèi)部元素而又不暴露該對象的內(nèi)部表示,這就是PHP迭代器模式的定義。

適用場景:

訪問一個聚合對象的內(nèi)容而無需暴露它的內(nèi)部表示

支持對聚合對象的多種遍歷

為遍歷不同的聚合結(jié)構(gòu)提供一個統(tǒng)一的接口

迭代器模式實例:

<?php

class ConcreteIterator implements Iterator{

 private $position = 0;

 private $arr;

 function __construct(array $arr){

 $this->arr = $arr;

 }

 function rewind(){

 $this->position = 0;

 }

 function current(){

 return $this->arr[$this->position];

 }

 function key(){

 return $this->position;

 }

 function next(){

 ++$this->position;

 }

 function valid(){

 return isset($this->arr[$this->position]);

 }

}

$arr = array('xiao hong','xiao ming','xiaohua');

$concreteIterator = new ConcreteIterator($arr);

foreach ($concreteIterator as $key => $value) {

 echo $key."=>".$value."\n";

}

以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)PHP設(shè)計模式有所幫助。

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:PHP設(shè)計模式之迭代器模式
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)