PHP設計模式之迭代器模式

來源:互聯網
上載者:User

概念

迭代器模式(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 <b>Iterator</b> or     * <b>Traversable</b>     * @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();}

這裡我們直接實現上面兩個介面,請看下面代碼:

<?phpheader('Content-type:text/html;charset=utf-8');/** * 迭代器模式 *//** * Class ConcreteIterator 具體的迭代器 */class ConcreteIterator implements Iterator{    private $position = 0;    private $array = array();    public function __construct($array) {        $this->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.'<hr>';            $iterator->next();        }    }}Client:: test();

運行結果:

鍵: 0 值: 屬性1
鍵: 1 值: 屬性2

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.