PHP设计模式漫谈之迭代器模式

原创
开发 后端
今天的PHP设计模式系列的主角是迭代器(Iterator)模式,迭代器模式提供了抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代。

【51CTO独家特稿】今天《PHP设计模式漫谈》系列的主角是迭代器(Iterator)模式,它在一个很常见的过程上提供了一个抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代。迭代有几种不同的具体执行方法:在数组属性,集合对象,数组,甚至一个查询结果集之上迭代。

在对象的世界里,迭代器模式要维持类似数组的功能,看作是一个非侵入性对象刻面(facet),Client类往往分离自真实对象实现,指iterator接口。只要有可能,我们可以给迭代器传送一个引用,代替将来可能发生变化的具体或抽象类。

迭代器模式 
图1 迭代器模式

参与者:

◆客户端(Client):引用迭代器模式的方法在一组值或对象上执行一个循环。

◆迭代器(Iterator):在迭代过程上的抽象,包括next(),isFinished(),current()等方法。

◆具体迭代器(ConcreteIterators):在一个特定的对象集,如数组,树,组合,集合等上实现迭代。

通过Traversable接口,PHP原生态支持迭代器模式,这个接口由Iterator和IteratorAggregate做了扩展,这两个子接口不仅是定义了一套标准的方法,每个Traversable对象都可以原封不动地传递给foreach(),foreach是迭代器的主要客户端,Iterator实现是真正的迭代器,而IteratorAggregate是有其它职责的Traversable对象,它通过getIterator()方法返回一个Iterator。

PHP架构

标准PHP库是PHP中绑定的唯一通用目的面向对象库,定义了额外的接口和公用类。OuterIterator实现装饰一个Iterator,CachingIterator和LimitIterator是这个接口的两个例子。

RecursiveIterator是Iterator接口为树形结构实现的一个扩展,它定义了一组额外的方法检查迭代中当前元素的子对象是否存在。RecursiveArrayIterator和RecursiveDirectoryIterator是这个接口的实现示例,这些类型的迭代器可以原样使用,或是用一个RecursiveIteratorIterator桥接到一个普通的迭代器契约。这个OuterIterator实现将会根据构造参数执行深度优先或广度优先遍历。

使用RecursiveIteratorIterator时,可以将其传递给foreach,请看后面的代码示例,了解RecursiveIterators的不同用法和它们的超集Iterator。最后,SeekableIterators向契约添加了一个seek()方法,它可以用于移动Iterator的内部状态到一个特定的迭代点。#p#

注意,迭代器是比对象集更好的抽象,因为我们可以让InfiniteIterators,NoRewindIterators等,不用与普通数组阵列与一致,因此,Iterator缺少count()函数等功能。
在PHP官方手册中可以找到完整的SPL迭代器列表。得益于对PHP的强力支持,使用迭代器模式的大部分工作都包括在标准实现中,下面的代码示例就利用了标准Iterator和RecursiveIterators的功能。

  1. <?php 
  2. /**  
  3.  * Collection that wraps a numeric array.  
  4.  * All five public methods are needed to implement  
  5.  * the Iterator interface.  
  6.  */  
  7. class Collection implements Iterator  
  8. {  
  9.     private $_content;  
  10.     private $_index = 0;  
  11.  
  12.     public function __construct(array $content)  
  13.     {  
  14.         $this->_content = $content;  
  15.     }  
  16.  
  17.     public function rewind()  
  18.     {  
  19.         $this->_index = 0;  
  20.     }  
  21.  
  22.     public function valid()  
  23.     {  
  24.         return isset($this->_content[$this->_index]);  
  25.     }  
  26.  
  27.     public function current()  
  28.     {  
  29.         return $this->_content[$this->_index];  
  30.     }  
  31.  
  32.     public function key()  
  33.     {  
  34.         return $this->_index;  
  35.     }  
  36.  
  37.     public function next()  
  38.     {  
  39.         $this->_index++;  
  40.     }  
  41. }  
  42.  
  43. $arrayarray = array('A', 'B', 'C', 'D');  
  44. echo "Collection: ";  
  45. foreach (new Collection($array) as $key => $value) {  
  46.     echo "$key => $value. ";  
  47. }  
  48. echo "\n"; 
  1. /**  
  2.  * Usually IteratorAggregate is the interface to implement.  
  3.  * It has only one method, which must return an Iterator  
  4.  * already defined as another class (e.g. ArrayIterator)  
  5.  * Iterator gives a finer control over the algorithm,  
  6.  * because all the hook points of Iterator' contract  
  7.  * are available for implementation.  
  8.  */  
  9. class NumbersSet implements IteratorAggregate  
  10. {  
  11.     private $_content;  
  12.  
  13.     public function __construct(array $content)  
  14.     {  
  15.         $this->_content = $content;  
  16.     }  
  17.  
  18.     public function contains($number)  
  19.     {  
  20.         return in_array($number, $this->_content);  
  21.     }  
  22.  
  23.     /**  
  24.      * Only this method is necessary to implement IteratorAggregate.  
  25.      * @return Iterator  
  26.      */  
  27.     public function getIterator()  
  28.     {  
  29.         return new ArrayIterator($this->_content);  
  30.     }  
  31. }  
  32.  
  33. echo "NumbersSet: ";  
  34. foreach (new NumbersSet($array) as $key => $value) {  
  35.     echo "$key => $value. ";  
  36. }  
  37. echo "\n"; 
  1. // let's play with RecursiveIterator implementations  
  2. $it = new RecursiveArrayIterator(array(  
  3.     'A',  
  4.     'B',  
  5.     array(  
  6.         'C',  
  7.         'D'  
  8.     ),  
  9.     array(  
  10.         array(  
  11.             'E',  
  12.             'F'  
  13.         ),  
  14.         array(  
  15.             'G',  
  16.             'H',  
  17.             'I'  
  18.         )  
  19.     )  
  20. ));  
  21. // $it is a RecursiveIterator but also an Iterator,  
  22. // so it loops normally over the four elements  
  23. // of the array.  
  24. echo "Foreach over a RecursiveIterator: ";  
  25. foreach ($it as $value) {  
  26.     echo $value;  
  27.     // but RecursiveIterators specify additional  
  28.     // methods to explore children nodes  
  29.     $children = $it->hasChildren() ? '{Yes}' : '{No}';  
  30.     echo $children, ' ';  
  31. }  
  32. echo "\n";  
  33. // we can bridge it to a different contract via  
  34. // a RecursiveIteratorIterator, whose cryptic name  
  35. // should be read as 'an Iterator that spans over  
  36. // a RecursiveIterator'.  
  37. echo "Foreach over a RecursiveIteratorIterator: ";  
  38. foreach (new RecursiveIteratorIterator($it) as $value) {  
  39.     echo $value;  
  40. }  
  41. echo "\n"; 

原文名:Practical Php Patterns: Iterator        作者:Giorgio

原文出处:http://giorgiosironi.blogspot.com/search/label/practical%20php%20patterns

【PHP设计模式系列】

  1. PHP设计模式漫谈之解释器模式
  2. PHP设计模式漫谈之工厂模式
  3. PHP设计模式漫谈之命令模式
  4. PHP设计模式漫谈之结构模式
  5. PHP设计模式漫谈之责任链模式
  6. PHP设计模式漫谈之代理模式
责任编辑:王晓东 来源: 51CTO.com
相关推荐

2010-04-21 08:38:18

解释器模式PHP设计模式

2010-04-13 08:54:28

PHP设计模式命令模式

2010-04-19 09:30:00

工厂模式PHP设计模式

2010-03-25 08:52:30

PHP设计模式代理模式

2010-04-01 09:10:03

PHP设计模式责任链模式

2010-04-08 09:27:04

PHP设计模式结构模式

2010-05-06 08:44:37

调解者模式

2021-06-22 15:27:13

设计模式迭代器模式Java

2020-11-06 09:01:46

迭代器模式

2023-09-04 13:14:00

装饰器设计模式

2023-12-13 13:28:16

装饰器模式Python设计模式

2011-04-21 09:46:41

设计模式

2021-01-04 09:43:24

Python 开发编程语言

2020-08-21 07:23:50

工厂模式设计

2009-08-26 16:26:37

C#迭代器模式

2009-08-11 13:59:41

迭代器模式C# Iterator

2015-09-08 13:39:10

JavaScript设计模式

2012-01-13 15:59:07

2021-06-16 08:56:06

模版方法模式设计模式行为型设计模式

2021-12-24 07:50:45

责任链模式设计
点赞
收藏

51CTO技术栈公众号