PHP设计模式入门之迭代器模式原理与实现方法分析
本文实例讲述了PHP设计模式入门之迭代器模式。分享给大家供大家参考,具体如下:
在深入研究这个设计模式之前,我们先来看一道面试题,来自鸟哥的博客,
题目是这样的:
使对象可以像数组一样进行foreach循环,要求属性必须是私有。
不使用迭代器模式很难实现,先看实现的代码:
sample.php
_arr=$arr;
}
publicfunctioncurrent(){
returncurrent($this->_arr);
}
publicfunctionnext(){
returnnext($this->_arr);
}
publicfunctionkey(){
returnkey($this->_arr);
}
publicfunctionvalid(){
return$this->current()!==false;
}
publicfunctionrewind(){
reset($this->_arr);
}
}
index.php
$v){
echo$k."-".$v."
";
}
其中Iterator接口来自php的spl类库,在写完设计模式的相关文章之后,将会进一步研究这个类库。
另外在网上找到了一段yii框架中关于迭代器模式的实现代码:
classCMapIteratorimplementsIterator{
/**
*@vararraythedatatobeiteratedthrough
*/
private$_d;
/**
*@vararraylistofkeysinthemap
*/
private$_keys;
/**
*@varmixedcurrentkey
*/
private$_key;
/**
*Constructor.
*@paramarraythedatatobeiteratedthrough
*/
publicfunction__construct(&$data){
$this->_d=&$data;
$this->_keys=array_keys($data);
}
/**
*Rewindsinternalarraypointer.
*ThismethodisrequiredbytheinterfaceIterator.
*/
publicfunctionrewind(){
$this->_key=reset($this->_keys);
}
/**
*Returnsthekeyofthecurrentarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnmixedthekeyofthecurrentarrayelement
*/
publicfunctionkey(){
return$this->_key;
}
/**
*Returnsthecurrentarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnmixedthecurrentarrayelement
*/
publicfunctioncurrent(){
return$this->_d[$this->_key];
}
/**
*Movestheinternalpointertothenextarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*/
publicfunctionnext(){
$this->_key=next($this->_keys);
}
/**
*Returnswhetherthereisanelementatcurrentposition.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnboolean
*/
publicfunctionvalid(){
return$this->_key!==false;
}
}
$data=array('s1'=>11,'s2'=>22,'s3'=>33);
$it=newCMapIterator($data);
foreach($itas$row){
echo$row,'
';
}
关于迭代器设计模式官方的定义是:使用迭代器模式来提供对聚合对象的统一存取,即提供一个外部的迭代器来对聚合对象进行访问和遍历,而又不需暴露该对象的内部结构。又叫做游标(Cursor)模式。
好吧,我不是很能理解。为什么明明数组已经可以用foreach来遍历了还要用这样一种迭代器模式来实现,只有等待工作经验的加深来进一步理解吧。
参考文档:
https://www.nhooo.com/article/184182.htm
https://www.nhooo.com/article/185478.htm
https://www.nhooo.com/article/185483.htm
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。