迭代器模式在不需要了解内部的前提下,遍历一个聚合对象的内部元素,相比传统的编程模式,迭代器模式可以隐藏遍历元素的所有操作
![1510713192607039.png `{`[~]5HUIA6J34Q[{C9FGG.png](https://img.php.cn//upload/image/845/927/305/1510713192607039.png)
<?php
/*
* 迭代器模式
*/
class All implements \Iterator
{
protected $ids;
protected $index;
public function __construct($data)
{
$this->ids = $data;
}
public function current() //获取当前的元素
{
return $this->ids[$this->index];
}
public function next() //获取下一个元素
{
$this->index++;
}
public function valid() //验证当下是否还有下一个元素
{
return $this->index < count($this->ids);
}
public function rewind() //重置迭代器指针
{
$this->index = 0;
}
public function key() //迭代器指针的位置
{
return $this->index;
}
}
$arr = ['1', '2', '4']; //客户端
$users = new All($arr);
foreach ($users as $user) {
var_dump($user);
}迭代器模式是一种使用频率非常高的设计模式,通过引入迭代器可以将数据的遍历功能从聚对象中分离出来,聚合对象只负责存储数据,而遍历数据由迭代器来完成
相关推荐:
立即学习“PHP免费学习笔记(深入)”;
以上就是PHP设计模式之迭代器模式详解的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号