php设计模式之迭代器模式

定义:迭代器模式在不需要了解内部实现的前提下,遍历一个一个聚合对象的内部元素,可以隐藏遍历元素所需的操作,让聚合对象的内部实现不暴露给访问者
实例:

<?php include 'db.php'; class MyIterator implements Iterator{ private $position = 0; //注意:被迭代对象属性是私有的 private $data = array(); public function __construct() { $this->position = 0; $db=Db::getInstance();//获得user的全部数据 $this->data=$db->getAll('user'); } function rewind() { //重置指针位置 $this->position = 0; } function current() { //获得当前指针指向的数据 return $this->data[$this->position]['username']; } function key() { //返回当前指针 return $this->position; } function next() { //指针移动到下一个位置 $this->position++; } function valid() { //判断当前指针是否溢出 return isset($this->data[$this->position]); } } $mi=new MyIterator(); while($mi->valid()){ print_r($mi->current()); echo "</br>"; $mi->next(); } $mi->rewind();

php设计模式之迭代器模式_第1张图片
输出为

wzw
zl
mtg
zl
wzw
wzw
fyj

你可能感兴趣的:(设计模式,PHP,迭代器)