PHP設計模式之迭代器模式詳解

來源:互聯網
上載者:User
迭代器模式在不需要瞭解內部的前提下,遍曆一個彙總對象的內部元素,相比傳統的編程模式,迭代器模式可以隱藏遍曆元素的所有操作

<?php/* * 迭代器模式 */class All implements \Iterator{    protected $ids;    protected $index;    public function __construct($data)    {        $this->ids = $data;    }    public function current() //擷取當前的元素    {        return $this->ids[$this->index];    }    public function next() //擷取下一個元素    {        $this->index++;    }    public function valid() //驗證當下是否還有下一個元素    {        return $this->index < count($this->ids);    }    public function rewind() //重設迭代器指標    {        $this->index = 0;    }    public function key() //迭代器指標的位置    {        return $this->index;    }}$arr = ['1', '2', '4']; //用戶端$users = new All($arr);foreach ($users as $user) {    var_dump($user);}

迭代器模式是一種使用頻率非常高的設計模式,通過引入迭代器可以將資料的遍曆功能從聚對象中分離出來,彙總對象只負責儲存資料,而遍曆資料由迭代器來完成

相關推薦:

星際爭霸之php迭代器模式

PHP變數引用 PHP迭代器模式(引用SPL實現)

php設計模式之觀察者模式詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.