设计模式十二:迭代器模式

迭代器模式:

  迭代器模式是提供一个顺序访问一个聚合对象中的各个元素,而不暴露对象内部。类似 for foreach。

<?php
class TestIterator implements Iterator{
     
    private $array;
    private $currentIndex = 0;

    public function __construct(array $array)
    {
        $this->array = $array;
    }

    /**
     * 初始化下标
     */
    function rewind()
    {
        echo '初始化下标'.PHP_EOL;
        $this->currentIndex = count($this->array)-1;
    }

    /**
     * 返回当前数据
     */
    function current()
    {
        echo '下标为'.$this->currentIndex.'的值为:'.PHP_EOL;
        return $this->array[$this->currentIndex].PHP_EOL;
    }

    /**
     * 索引指向下一个
     */
    function next(){
        --$this->currentIndex;
    }

    /**
     * 返回当前下标
     */
    function key()
    {
        return $this->currentIndex;
    }

    /**
     * 判断是否有下一个元素
     */
    function valid()
    {
        echo '下标为'.$this->currentIndex.'判断是否有值';
        return isset($this->array[$this->currentIndex]);
    }
 }

 $list = [1,2,3,4,5,6,7,8,9,10];
 $test = new TestIterator($list);
 foreach($test as $t){
     echo $t;
 }

posted @ 2021-08-26 17:31  wish_yang  阅读(33)  评论(0编辑  收藏  举报