迭代器模式
迭代器模式:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示.
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/2/27
* Time: 10:45
*/
namespace frontend\models;
abstract class Iterator
{
public abstract function First();
public abstract function Next();
public abstract function IsDone();
public abstract function CurrentItem();
}
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/2/27
* Time: 10:47
*/
namespace frontend\models;
class ConcreteIterator extends Iterator
{
private $arr;
private $current = 0;
public function __construct($arr)
{
$this->arr = $arr;
}
//访问第一个元素
public function First()
{
if (empty($this->arr))
return null;
return $this->arr[0];
}
//访问下一个元素
public function Next()
{
$this->current++;
if($this->current>count($this->arr)){
return $this->arr[$this->current];
}
return false;
}
//判断是否遍历完毕
public function IsDone()
{
// TODO: Implement IsDone() method.
return $this->current >= count($this->arr) ? true:false;
}
//返回当前聚集对象
public function CurrentItem()
{
return $this->arr[$this->current];
}
}
$iterator = new ConcreteIterator(['pig','dog','cat','fish','goose','swan','duck']);
echo $iterator->First()."<br>";
$iterator->Next();
echo $iterator->CurrentItem()."<br>";
使用场景:
1.访问一个聚合对象的内容而无需暴露它的内部表示
2.支持对聚合对象的多种遍历
3.为遍历不同的聚合结构提供一个统一的接口