Home  >  Article  >  php教程  >  PHP设计模式之迭代器模式,php设计模式

PHP设计模式之迭代器模式,php设计模式

WBOY
WBOYOriginal
2016-07-06 14:24:46761browse

PHP设计模式之迭代器模式,php设计模式

在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素而又不暴露该对象的内部表示,这就是PHP迭代器模式的定义。

适用场景:
访问一个聚合对象的内容而无需暴露它的内部表示
支持对聚合对象的多种遍历
为遍历不同的聚合结构提供一个统一的接口

迭代器模式实例:

<&#63;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设计模式有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn