PHP 设计模式系列 -- 迭代器模式(Iterator)

php中文网
发布: 2016-06-20 12:41:33
原创
1087人浏览过

1、模式定义

迭代器模式 (iterator),又叫做游标(cursor)模式。提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。

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

追梦flash企业网站管理模板A系列11.0
追梦flash企业网站管理模板A系列11.0

追梦A系列(11.0版本,以下11.0均简称为A)是针对企业网站定制设计的,模板采用全新AS3.0代码编辑,拥有更快的运行和加载速度,A系列模板主要针对图片展示,拥有简洁大气展示效果,并且可以自由扩展图片分类,同时还拥有三个独立页面介绍栏目,一个新闻栏目,一个服务介绍栏目,一个幻灯片展示和flv视频播放栏目。A系列模板对一些加载效果进行了修改,包括背景的拉伸模式以及标题的展示方式等都进行了调整,同

追梦flash企业网站管理模板A系列11.0 0
查看详情 追梦flash企业网站管理模板A系列11.0

PHP标准库(SPL)中提供了迭代器接口 Iterator,要实现迭代器模式,实现该接口即可。

2、UML类图

3、示例代码

Book.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class Book{    private $author;    private $title;    public function __construct($title, $author)    {        $this->author = $author;        $this->title = $title;    }    public function getAuthor()    {        return $this->author;    }    public function getTitle()    {        return $this->title;    }    public function getAuthorAndTitle()    {        return $this->getTitle() . ' by ' . $this->getAuthor();    }}
登录后复制

BookList.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookList implements \Countable{    private $books;    public function getBook($bookNumberToGet)    {        if (isset($this->books[$bookNumberToGet])) {            return $this->books[$bookNumberToGet];        }        return null;    }    public function addBook(Book $book)    {        $this->books[] = $book;    }    public function removeBook(Book $bookToRemove)    {        foreach ($this->books as $key => $book) {            /** @var Book $book */            if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {                unset($this->books[$key]);            }        }    }    public function count()    {        return count($this->books);    }}
登录后复制

BookListIterator.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookListIterator implements \Iterator{    /**     * @var BookList     */    private $bookList;    /**     * @var int     */    protected $currentBook = 0;    public function __construct(BookList $bookList)    {        $this->bookList = $bookList;    }    /**     * Return the current book     * @link http://php.net/manual/en/iterator.current.php     * @return Book Can return any type.     */    public function current()    {        return $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Move forward to next element     * @link http://php.net/manual/en/iterator.next.php     * @return void Any returned value is ignored.     */    public function next()    {        $this->currentBook++;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * 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.     */    public function key()    {        return $this->currentBook;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * 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.     */    public function valid()    {        return null !== $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Rewind the Iterator to the first element     * @link http://php.net/manual/en/iterator.rewind.php     * @return void Any returned value is ignored.     */    public function rewind()    {        $this->currentBook = 0;    }}
登录后复制

BookListReverseIterator.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookListReverseIterator implements \Iterator{    /**     * @var BookList     */    private $bookList;    /**     * @var int     */    protected $currentBook = 0;    public function __construct(BookList $bookList)    {        $this->bookList = $bookList;        $this->currentBook = $this->bookList->count() - 1;    }    /**     * Return the current book     * @link http://php.net/manual/en/iterator.current.php     * @return Book Can return any type.     */    public function current()    {        return $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Move forward to next element     * @link http://php.net/manual/en/iterator.next.php     * @return void Any returned value is ignored.     */    public function next()    {        $this->currentBook--;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * 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.     */    public function key()    {        return $this->currentBook;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * 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.     */    public function valid()    {        return null !== $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Rewind the Iterator to the first element     * @link http://php.net/manual/en/iterator.rewind.php     * @return void Any returned value is ignored.     */    public function rewind()    {        $this->currentBook = $this->bookList->count() - 1;    }}
登录后复制

4、测试代码

Tests/IteratorTest.php

<?phpnamespace DesignPatterns\Behavioral\Iterator\Tests;use DesignPatterns\Behavioral\Iterator\Book;use DesignPatterns\Behavioral\Iterator\BookList;use DesignPatterns\Behavioral\Iterator\BookListIterator;use DesignPatterns\Behavioral\Iterator\BookListReverseIterator;class IteratorTest extends \PHPUnit_Framework_TestCase{    /**     * @var BookList     */    protected $bookList;    protected function setUp()    {        $this->bookList = new BookList();        $this->bookList->addBook(new Book('Learning PHP Design Patterns', 'William Sanders'));        $this->bookList->addBook(new Book('Professional Php Design Patterns', 'Aaron Saray'));        $this->bookList->addBook(new Book('Clean Code', 'Robert C. Martin'));    }    public function expectedAuthors()    {        return array(            array(                array(                    'Learning PHP Design Patterns by William Sanders',                    'Professional Php Design Patterns by Aaron Saray',                    'Clean Code by Robert C. Martin'                )            ),        );    }    /**     * @dataProvider expectedAuthors     */    public function testUseAIteratorAndValidateAuthors($expected)    {        $iterator = new BookListIterator($this->bookList);        while ($iterator->valid()) {            $expectedBook = array_shift($expected);            $this->assertEquals($expectedBook, $iterator->current()->getAuthorAndTitle());            $iterator->next();        }    }    /**     * @dataProvider expectedAuthors     */    public function testUseAReverseIteratorAndValidateAuthors($expected)    {        $iterator = new BookListReverseIterator($this->bookList);        while ($iterator->valid()) {            $expectedBook = array_pop($expected);            $this->assertEquals($expectedBook, $iterator->current()->getAuthorAndTitle());            $iterator->next();        }    }    /**     * Test BookList Remove     */    public function testBookRemove()    {        $this->bookList->removeBook($this->bookList->getBook(0));        $this->assertEquals($this->bookList->count(), 2);    }}
登录后复制
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号