时间:2021-07-01 10:21:17 帮助过:3人阅读
迭代器模式:迭代器模式是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个叫做迭代器的对象,它的工作时遍历并选择序列中的对象,而客户端程序员不必知道或关心该集合序列底层的结构。
UML类图:

角色:
Iterator(迭代器):迭代器定义访问和遍历元素的接口
ConcreteIterator(具体迭代器):具体迭代器实现迭代器接口,对该聚合遍历时跟踪当前位置
Aggregate (聚合):聚合定义创建相应迭代器对象的接口(可选)
ConcreteAggregate(具体聚合):具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例(可选)
核心代码:
aggre = $_aggre;
}
//返回第一个
public function First()
{
return $this->aggre[0];
}
//返回下一个
public function Next()
{
$this->current++;
if($this->currentaggre))
{
return $this->aggre[$this->current];
}
return false;
}
//返回是否IsDone
public function IsDone()
{
return $this->current>=count($this->aggre)?true:false;
}
//返回当前聚集对象
public function CurrentItem()
{
return $this->aggre[$this->current];
}
}
header(Content-Type:text/html;charset=utf-8);
//--------------------------迭代器模式-------------------
require_once ./Iterator/Iterator.php;
$iterator= new ConcreteIterator(array('周杰伦','王菲','周润发'));
$item = $iterator->First();
echo $item.
;
while(!$iterator->IsDone())
{
echo {$iterator->CurrentItem()}:请买票!
;
$iterator->Next();
}
1.访问一个聚合对象的内容而无需暴露它的内部表示
2.支持对聚合对象的多种遍历
3.为遍历不同的聚合结构提供一个统一的接口
欢迎关注我的视频课程,地址如下,谢谢。
PHP面向对象设计模式
http://www.bkjia.com/PHPjc/1015086.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1015086.htmlTechArticlePHP设计模式——迭代器模式 迭代器模式:迭代器模式是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个叫做迭代器的...