迭代器模式简介与面试案例
本文将详细介绍PHP设计模式中的迭代器模式,并通过具体实例帮助读者掌握其核心原理与应用方法,供学习参考。
在进入迭代器模式的深入探讨之前,我们先回顾一道经典的面试题,这道题源自鸟哥的博客文章。
题目的具体要求如下:
需要实现一个功能,使得自定义对象能够像数组一样支持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);
}
}
主入口文件命名为index.php
<?php
require 'Sample.php';
$arr = new Sample(['max', 'ben', 'will']);
foreach ($arr as $k=>$v){
echo $k."-".$v."
";
}
上述实现中使用的Iterator接口来源于PHP的标准库(SPL)。在后续完成设计模式系列文章后,我们将进一步深入研究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遍历,为何还要特意使用迭代器模式来实现?这背后的深层原因可能需要随着实际工作经验的积累才能更深刻地理解。
以下是本文参考的相关文档链接:
https://www.jb51.net/article/184182.htm
https://www.jb51.net/article/185478.htm
https://www.jb51.net/article/185483.htm
希望本文的内容能对各位的PHP程序设计学习有所帮助。