php与设计模式-迭代器模式

本文深入讲解了迭代器模式,一种成熟的遍历集合的模式。通过将遍历任务交给迭代器对象,客户端程序员可以无需了解底层集合结构即可进行操作。文章提供了PHP实现的迭代器模式示例,展示了如何创建抽象迭代器和具体迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迭代器模式

迭代器模式是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个叫做迭代器的对象,它的工作时遍历并选择序列中的对象,而客户端程序员不必知道或关心该集合序列底层的结构。

Demo

<?php   
//抽象迭代器 
abstract class IIterator 
{ 
    public abstract function First(); 
    public abstract function Next(); 
    public abstract function IsDone(); 
    public abstract function CurrentItem(); 
} 
//具体迭代器 
class ConcreteIterator extends IIterator 
{ 
    private $aggre; 
    private $current = 0; 
    public function __construct(array $_aggre) 
    { 
        $this->aggre = $_aggre; 
    } 
    //返回第一个 
    public function First() 
    { 
        return $this->aggre[0]; 
    } 
    //返回下一个 
    public function  Next() 
    { 
        $this->current++; 
        if($this->current<count($this->aggre)) 
        { 
            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]; 
    } 
}
 
$iterator= new ConcreteIterator(array('周杰伦','王菲','周润发')); 
$item = $iterator->First(); 
echo $item."<br/>"; 
while(!$iterator->IsDone()) 
{ 
    echo "{$iterator->CurrentItem()}:请买票!<br/>"; 
    $iterator->Next(); 
}
?>

请关注我的订阅号

订阅号.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码哥说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值