时间:2021-07-01 10:21:17 帮助过:22人阅读
适用场景:
访问一个聚合对象的内容而无需暴露它的内部表示
支持对聚合对象的多种遍历
为遍历不同的聚合结构提供一个统一的接口
迭代器模式实例:
- <?php
- class ConcreteIterator implements Iterator{
- private $position = 0;
- private $arr;
- function __construct(array $arr){
- $this->arr = $arr;
- }
- function rewind(){
- $this->position = 0;
- }
- function current(){
- return $this->arr[$this->position];
- }
- function key(){
- return $this->position;
- }
- function next(){
- ++$this->position;
- }
- function valid(){
- return isset($this->arr[$this->position]);
- }
- }
- $arr = array('xiao hong','xiao ming','xiaohua');
- $concreteIterator = new ConcreteIterator($arr);
- foreach ($concreteIterator as $key => $value) {
- echo $key."=>".$value."\n";
- }
以上就是本文的全部内容,希望对大家学习PHP设计模式有所帮助。