从而公开表示法这种模式提供了一种方法来访问聚合对象的元素从而无需公开其底层表示法
ConcreteIterator(具体迭代器)
This class (a) implements the Iterator interface and (b) keeps track of the current position in the traversal(遍历) of the aggregate(集合).
(这类(a)实现了迭代器接口和(b)在遍历的集合中,跟踪当前位置。)
Iterator(迭代器)
This class defines an interface for accessing and traversing(遍历) elements.
(这个类定义了一个接口来访问和遍历元素。)
ConcreteAggregate(具体的集合)
This class implements the Iterator creation interface to return an instance of the proper ConcreteIterator.
(这个类实现了迭代器创建接口返回的一个适当的ConcreteIterator实例。)
Aggregate(集合)
This class defines an interface for creating an Iterator object.
(这个类定义了一个接口来创建一个迭代器对象。)
<?php
class ConcreteIterator extends abstract_Iterator
{
private $aggregate = array();
private $current = 0;
/**
* 获取集合
* @param $aggregate
*/
public function __construct($aggregate)
{
$this->aggregate = $aggregate;
}
/**
* 第一个对象
* @see abstract_Iterator::first()
*/
public function first()
{
return $this->aggregate[0];
}
/**
* 下一个对象
* @see abstract_Iterator::next()
*/
public function next()
{
$this->current++;
if ($this->current < count($this->aggregate) + 1) {
return $this->aggregate[$this->current - 1];
}
}
/**
* 判断是否到结尾
* @see abstract_Iterator::isdone()
*/
public function isdone()
{
return $this->current >= count($this->aggregate) ? true : false;
}
/**
* 返回当前对象
*/
public function currentitem()
{
return $this->aggregate[$current];
}
}
abstract class abstract_Iterator
{
abstract public function first();
abstract public function next();
abstract public function isdone();
abstract public function currentitem();
}
class ConcreteAggregate extends abstract_Aggregate
{
private $list = array();
public function createiterator()
{
return new ConcreteIterator($this->getlist());
}
public function count()
{
return count($this->list);
}
public function getlist()
{
return $this->list;
}
public function setlist($list)
{
$this->list[] = $list;
}
}
abstract class abstract_Aggregate
{
abstract public function createiterator();
}
$concreteaggregate = new ConcreteAggregate();
$concreteaggregate->setlist("A");
$concreteaggregate->setlist("B");
$concreteaggregate->setlist("C");
$i = $concreteaggregate->createiterator();
echo $i->first();
while (!$i->isdone()) {
echo $i->next();
}
评论