您好,欢迎访问一九零五行业门户网

设计模式入门-迭代器模式(php版)

在深入研究这个设计模式之前,我们先来看一道面试题,来自鸟哥的博客,
题目是这样的:
使对象可以像数组一样进行foreach循环,要求属性必须是私有。
不使用迭代器模式很难实现,先看实现的代码:
sample.php
_arr = $arr; } public function current(){ return current($this->_arr); } public function next(){ return next($this->_arr); } public function key(){ return key($this->_arr); } public function valid(){ return $this->current() !== false; } public function rewind(){ reset($this->_arr); }}
index.php$v){ echo $k.-.$v.
;}
其中iterator接口来自php的spl类库,在写完设计模式的相关文章之后,将会进一步研究这个类库。
另外在网上找到了一段yii框架中关于迭代器模式的实现代码:
class cmapiterator implements iterator {/*** @var array the data to be iterated through*/ private $_d;/*** @var array list of keys in the map*/ private $_keys;/*** @var mixed current key*/ private $_key; /*** constructor.* @param array the data to be iterated through*/ public function __construct(&$data) { $this->_d=&$data; $this->_keys=array_keys($data); } /*** rewinds internal array pointer.* this method is required by the interface iterator.*/ public function rewind() { $this->_key=reset($this->_keys); } /*** returns the key of the current array element.* this method is required by the interface iterator.* @return mixed the key of the current array element*/ public function key() { return $this->_key; } /*** returns the current array element.* this method is required by the interface iterator.* @return mixed the current array element*/ public function current() { return $this->_d[$this->_key]; } /*** moves the internal pointer to the next array element.* this method is required by the interface iterator.*/ public function next() { $this->_key=next($this->_keys); } /*** returns whether there is an element at current position.* this method is required by the interface iterator.* @return boolean*/ public function valid() { return $this->_key!==false; }} $data = array('s1' => 11, 's2' => 22, 's3' => 33);$it = new cmapiterator($data);foreach ($it as $row) { echo $row, '
';}
关于迭代器设计模式官方的定义是:使用迭代器模式来提供对聚合对象的统一存取,即提供一个外部的迭代器来对聚合对象进行访问和遍历 , 而又不需暴露该对象的内部结构。又叫做游标(cursor)模式。
好吧,我不是很能理解。为什么明明数组已经可以用foreach来遍历了还要用这样一种迭代器模式来实现,只有等待工作经验的加深来进一步理解吧。
参考文档:
http://www.cnblogs.com/davidhhuan/p/4248206.html
http://blog.csdn.net/hguisu/article/details/7552841
http://www.phppan.com/2010/04/php-iterator-and-yii-cmapiterator/
php源码阅读笔记二十四 :iterator实现中当值为false时无法完成迭代的原因分析:http://www.phppan.com/2010/04/php-source-24-iterator-false-value/
以上就介绍了设计模式入门-迭代器模式(php版),包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息