在深入研究這個設計模式之前,我們先來看一道面試題,來自鳥哥的博客,
題目是這樣的:
使對象可以像數組一樣進行foreach循環,要求屬性必須是私有。
不使用迭代器模式很難實現,先看實現的程式碼:
sample.php
<?php class Sample implements Iterator{ private $_arr; public function __construct(Array $arr){ $this->_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); } }
<?php require 'Sample.php'; $arr = new Sample(['max', 'ben', 'will']); foreach ($arr as $k=>$v){ echo $k."-".$v."<br />"; }
其中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, '<br />'; }
關於迭代器設計模式官方的定義是:使用迭代器模式來提供對聚合對象的統一訪問,即提供一個外部的迭代器來對聚合物件進行存取和遍歷, 而又不需暴露該物件的內部結構。又叫做遊標(Cursor)模式。
好吧,我不是很能理解。為什麼明明數組已經可以用foreach來遍歷了還要用這樣一種迭代器模式來實現,只有等待工作經驗的加深來進一步理解吧。
參考文件:
http://www.cnblogs.com/davidhhuan/p/4248206.html
http://blog.csdn.net/hguisu/article/details/7552841 www.phppan.com/2010/04/php-iterator-and-yii-cmapiterator/
以上就介紹了設計模式入門-迭代器模式(php版),包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。