php實現設計模式之 迭代器模式

來源:互聯網
上載者:User

標籤:blog   http   io   ar   使用   div   on   log   cti   

<?php/*迭代器模式: 提供一種方法順序訪問一個彙總對象中各個元素, 而又不需暴露該對象的內部表示。(行為模式) * 1.迭代器角色(Iterator):迭代器角色負責定義訪問和遍曆元素的介面。 2.具體迭代器角色(Concrete Iterator):具體迭代器角色要實現迭代器介面,並要記錄遍曆中的當前位置。 3.集合角色(Aggregate):集合角色負責提供建立具體迭代器角色的介面。 4.具體集合角色(Concrete Aggregate):具體集合角色實現建立具體迭代器角色的介面——這個具體迭代器角色於該集合的結構相關。 *//** * 迭代器介面,定義訪問和遍曆元素的操作 */interface IIterator{//移動到彙總對象的第一個元素位置public function first();//移動到彙總對象的下一個元素位置public function next();/** * 判斷是否已經移動到彙總對象的最後一個位置 * true 表示移動到了彙總對象的最後一個位置 * false 表示還沒有移動到彙總對象的最後一個位置 */public function isDone();/** * 取得迭代的當前元素   * 返回迭代的當前元素 */public function currentItem();} /** * 具體的迭代器實現對象,示意的是彙總對象為數組的迭代器 * 不同的彙總對象相應的迭代器的實現是不同的 */ class ConcreteIterator implements IIterator{//持有被迭代的具體彙總對象private $aggregate;/** * 內部索引,記錄當前迭代到的索引位置 * -1表示剛剛開始的時候,迭代器指向彙總對象第一個對象之前 */private $index = -1;private $aggregateCount = null;/** * 建構函式,傳入被迭代的具體彙總對象 * @param $aggregate 被迭代的具體彙總對象 */public function __construct($aggregate){$this->aggregate = $aggregate;$this->aggregateCount = $this->aggregate->getCounts();} public function first(){$this->index = 0;} public function next(){if($this->index < $this->aggregateCount){$this->index = $this->index + 1;}} public function isDone(){if($this->index == $this->aggregateCount){return true;}return false;} public function currentItem(){return $this->aggregate->getItem($this->index);} public function getAggregateCount(){return $this->aggregateCount;}} /** * 彙總對象的抽象類別,定義了建立相應迭代器對象的介面,每一個實現該彙總對象抽象類別的對象都要實現這個抽象方法 */abstract class Aggregate{public abstract function createIterator();} /** * 具體的彙總對象,實現建立相應迭代器對象的功能 */class ConcreteAggregate extends Aggregate{//彙總對象的具體內容private $arrayAgg = null; /** * 建構函式:傳入彙總對象具體的內容,在這個例子中是數組 * @param $arrayAgg 彙總對象的具體內容 */ public function __construct($arrayAgg){$this->arrayAgg = $arrayAgg;} public function createIterator(){//實現建立Iterator的Factory 方法return new ConcreteIterator($this);} public function getItem($index){if($index < sizeof($this->arrayAgg)){return $this->arrayAgg[$index];}} public function getCounts(){return sizeof($this->arrayAgg);}} /** * 看看具體的使用方法 */$aggregate = new ConcreteAggregate(array(‘張三‘,‘李四‘,‘王五‘));$iterator = $aggregate->createIterator(); $iterator->first();while(!$iterator->isDone()){$obj = $iterator->currentItem();echo "The obj == ".$obj."<br>";$iterator->next();}?>

  UML

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.