PHP设计模式(6)迭代器模式

简介:

迭代器(Iterator)模式,在一个很常见的过程上提供了一个抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代。

迭代有几种不同的具体执行方法:在数组属性,集合对象,数组,甚至一个查询结果集之上迭代。

在PHP官方手册中可以找到完整的SPL迭代器列表。得益于对PHP的强力支持,使用迭代器模式的大部分工作都包括在标准实现中,下面的代码示例就利用了标准Iterator的功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
//定义一个类,实现了Iterator的方法
class  testIterator  implements  Iterator {
private  $_content ;
private  $_index  = 0;
//构造函数
public  function  __construct( array  $content ) {
$this ->_content =  $content ;
}
//返回到迭代器的第一个元素
public  function  rewind () {
$this ->_index = 0;
}
//检查当前位置是否有效
public  function  valid() {
return  isset( $this ->_content[ $this ->_index]);
}
//返回当前元素
public  function  current() {
return  $this ->_content[ $this ->_index];
}
//返回当前元素的键
public  function  key() {
return  $this ->_index;
}
//向前移动到下一个元素
public  function  next() {
$this ->_index++;
}
}
//定义数组,生成类时使用
$arrString  array ( 'jane' , 'apple' , 'orange' , 'pear' );
$testIterator  new  testIterator( $arrString );
//开始迭代对象
foreach  $testIterator  as  $key  =>  $val  ) {
echo  $key  '=>'  $val  '<br>' ;
}

运行可以看到如下结果:

1
2
3
4
0=>jane
1=>apple
2=>orange
3=>pear

如果有兴趣,可以在每一个函数里面开始处加上“var_dump(__METHOD__);”,这样就可以看到每个函数的调用顺序了,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string(25)  "testIterator::__construct"
string(20)  "testIterator::rewind"
string(19)  "testIterator::valid"
string(21)  "testIterator::current"
string(17)  "testIterator::key"
0=>jane
string(18)  "testIterator::next"
string(19)  "testIterator::valid"
string(21)  "testIterator::current"
string(17)  "testIterator::key"
1=>apple
string(18)  "testIterator::next"
string(19)  "testIterator::valid"
string(21)  "testIterator::current"
string(17)  "testIterator::key"
2=>orange
string(18)  "testIterator::next"
string(19)  "testIterator::valid"
string(21)  "testIterator::current"
string(17)  "testIterator::key"
3=>pear
string(18)  "testIterator::next"
string(19)  "testIterator::valid"




















本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1344851 ,如需转载请自行联系原作者
相关文章
|
16天前
|
设计模式 算法 PHP
php设计模式--策略模式(六)
php设计模式--策略模式(六)
11 0
|
16天前
|
设计模式 PHP
php设计模式--装饰模式(七)装饰模式完成文章编辑
php设计模式--装饰模式(七)装饰模式完成文章编辑
10 0
|
4月前
|
设计模式 Java
Java设计模式【十七】:迭代器模式
Java设计模式【十七】:迭代器模式
31 0
|
6月前
|
设计模式 C++ 容器
设计模式之迭代器模式(C++)
设计模式之迭代器模式(C++)
|
4月前
|
设计模式
二十三种设计模式全面解析-组合模式与迭代器模式的结合应用:构建灵活可扩展的对象结构
二十三种设计模式全面解析-组合模式与迭代器模式的结合应用:构建灵活可扩展的对象结构
|
6月前
|
设计模式
设计模式14 - 迭代器模式【Iterator Pattern】
设计模式14 - 迭代器模式【Iterator Pattern】
15 0
|
2天前
|
设计模式 Go
[设计模式 Go实现] 行为型~迭代器模式
[设计模式 Go实现] 行为型~迭代器模式
|
13天前
|
设计模式 Java
小谈设计模式(21)—迭代器模式
小谈设计模式(21)—迭代器模式
|
16天前
|
设计模式 PHP
php设计模式--责任链模式(五)
php设计模式--责任链模式(五)
13 0
|
1月前
|
设计模式 存储 算法
【设计模式】迭代器模式
【设计模式】迭代器模式