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

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

適用場景:

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

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

為遍歷不同的聚合結構提供一個統(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";

}

以上就是本文的全部內容,希望對大家學習PHP設計模式有所幫助。

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:PHP設計模式之迭代器模式
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點

版權所有:易賢網(wǎng)