资讯专栏INFORMATION COLUMN

PHP设计模式之迭代器模式

陆斌 / 995人阅读

摘要:概念迭代器模式,又叫做游标模式。另外,当需要对聚集有多种方式遍历时,可以考虑去使用迭代器模式。迭代器模式为遍历不同的聚集结构提供如开始下一个是否结束当前哪一项等统一的接口。

概念

迭代器模式(Iterator),又叫做游标(Cursor)模式。提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。

当你需要访问一个聚合对象,而且不管这些对象是什么都需要遍历的时候,就应该考虑使用迭代器模式。另外,当需要对聚集有多种方式遍历时,可以考虑去使用迭代器模式。迭代器模式为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪一项等统一的接口。

适用场景

访问一个聚合对象的内容而无需暴露它的内部表示

支持对聚合对象的多种遍历

为遍历不同的聚合结构提供一个统一的接口

UML图

角色

Iterator(迭代器):迭代器定义访问和遍历元素的接口

ConcreteIterator(具体迭代器):具体迭代器实现迭代器接口,对该聚合遍历时跟踪当前位置

Aggregate (聚合): 聚合定义创建相应迭代器对象的接口

ConcreteAggregate (具体聚合):具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例

代码

代码如下:

PHP SPL中已经提供了迭代器接口Iterator和容器接口IteatorAggragate,其源码如下:

/**
 * Interface to detect if a class is traversable using &foreach;.
 * @link http://php.net/manual/en/class.traversable.php
 */
interface Traversable {
}

/**
 * Interface to create an external Iterator.
 * @link http://php.net/manual/en/class.iteratoraggregate.php
 */
interface IteratorAggregate extends Traversable {

    /**
     * Retrieve an external iterator
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable An instance of an object implementing Iterator or
     * Traversable
     * @since 5.0.0
     */
    public function getIterator();
}

/**
 * Interface for external iterators or objects that can be iterated
 * themselves internally.
 * @link http://php.net/manual/en/class.iterator.php
 */
interface Iterator extends Traversable {

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current();

    /**
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next();

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key();

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid();

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind();
}

这里我们直接实现上面两个接口,请看下面代码:

array = $array;
        $this->position = 0;
    }

    function rewind() {
        $this->position = 0;
    }

    function current() {
        return $this->array[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->array[$this->position]);
    }
}

/**
 * Class MyAggregate 聚合容器
 */
class ConcreteAggregate implements IteratorAggregate
{
    public $property;

    /**
     * 添加属性
     *
     * @param $property
     */
    public function addProperty($property)
    {
        $this->property[] = $property;
    }

    public function getIterator()
    {
        return new ConcreteIterator($this->property);
    }
}

/**
 * Class Client 客户端测试
 */
class Client
{
    public static function test()
    {
        //创建一个容器
        $concreteAggregate = new ConcreteAggregate();
        // 添加属性
        $concreteAggregate->addProperty("属性1");
        // 添加属性
        $concreteAggregate->addProperty("属性2");
        //给容器创建迭代器
        $iterator = $concreteAggregate->getIterator();
        //遍历
        while($iterator->valid())
        {
            $key   = $iterator->key();
            $value = $iterator->current();
            echo "键: ".$key." 值: ".$value."
"; $iterator->next(); } } } Client:: test();

运行结果:

键: 0 值: 属性1
键: 1 值: 属性2

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/22074.html

相关文章

  • PHP基础

    摘要:分别为适配器模式,装饰器模式,代理模式,外观模式,桥接模式,组合模式,享元模式。设计模式五适配器模式适配器模式将某个对象的接生成器和协程的实现在这篇文章中,作者针对那些比较难以理解的概念,以一个更为通俗的方式去讲明白。。 PHP 源码注解 PHP 的详细源码注解 PHP 字符串操作整理 一些有关字符串的常用操作。 Redis 常见七种使用场景 (PHP 实战) 这篇文章主要介绍利用 R...

    HtmlCssJs 评论0 收藏0
  • php设计模式

    摘要:我们今天也来做一个万能遥控器设计模式适配器模式将一个类的接口转换成客户希望的另外一个接口。今天要介绍的仍然是创建型设计模式的一种建造者模式。设计模式的理论知识固然重要,但 计算机程序的思维逻辑 (54) - 剖析 Collections - 设计模式 上节我们提到,类 Collections 中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了...

    Dionysus_go 评论0 收藏0
  • php设计模式

    摘要:我们今天也来做一个万能遥控器设计模式适配器模式将一个类的接口转换成客户希望的另外一个接口。今天要介绍的仍然是创建型设计模式的一种建造者模式。设计模式的理论知识固然重要,但 计算机程序的思维逻辑 (54) - 剖析 Collections - 设计模式 上节我们提到,类 Collections 中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了...

    vspiders 评论0 收藏0
  • PHP SplObjectStorage对象存储

    摘要:类实现了对象存储映射表,应用于需要唯一标识多个对象的存储场景。在之前仅能存储对象,之后可以针对每个对象添加一条对应的数据。实际上他们并没有直接的关系。 1. 定义 php.net上的定义 The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. ...

    cpupro 评论0 收藏0
  • PHP迭代和生成

    摘要:生成器的内部一直在停顿和恢复之间切换,直到循环完成或停顿位置缺点生成器不能满足所有迭代器的需求,因为如果不查询,生成器永远不知道下一个要迭代的值是什么,在生成器中无法后退或前进。 一.迭代器 分析:想一下,如果把集合对象和对集合对象的操作放在一起,当我们想换一种方式遍历集合对象中元素时,就需要修改集合对象了,违背单一职责原则,而迭代器模式将数据结构和数据结构的算法分离开,两者可独立发展...

    sanyang 评论0 收藏0

发表评论

0条评论

陆斌

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<