定义
迭代器模式(Iterator Pattern)用于顺序访问集合对象的元素,而不暴露该对象的内部表示。
代码示例
建立 Iterator 迭代器接口,定义遍历方法,定义ConcreteInterator 接口实现聚合对象接口。
<?php
namespace IteratorPattern11;
interface Iterator
{
public function next();
public function isDone();
public function current();
public function first();
}
class ConcreteIterator implements Iterator
{
private $concrete;
private static $index = 0;
public function __construct($arg)
{
$this->concrete = $arg;
}
public function next()
{
self::$index++;
if(self::$index < count($this->concrete)){
return $this->concrete[self::$index];
}
return '索引错误';
}
public function isDone()
{
return self::$index >= count($this->concrete) ? true : false;
}
public function current()
{
return $this->concrete[self::$index];
}
public function first()
{
return $this->concrete[0];
}
}
interface Aggregate
{
public function createIterator();
}
class ConcreteAggregate implements Aggregate
{
public $username;
public function __construct()
{
$this->username = ['张三','李四','王五','赵六'];
}
public function createIterator()
{
return new ConcreteIterator($this->username);
}
}
class DemoPattern
{
public function handle()
{
$aggregate = new ConcreteAggregate();
$agr = $aggregate->createIterator();
echo $agr->current();
echo $agr->next();
echo $agr->next();
echo $agr->next();
echo $agr->next();
}
}
$demoPattern = new DemoPattern();
$demoPattern->handle();
总结
当一个聚集由多种方式遍历时,可以考虑使用该模式,不过目前各种流行语言已经将迭代器作为底层的类库了,平时开发基本用不到,弄懂原理就可以了。
网友评论