Heim  >  Artikel  >  php教程  >  PHP设计模式之迭代器模式,php设计模式

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn