PHP设计模式——迭代模式
聲明:這一系列的博客引用《大話設計模式》。程潔作者。
?????? 迭代器模式:迭代器模式是遍歷集合的成熟模式。迭代器模式的關鍵是將遍歷集合的任務交給一個叫做迭代器的對象,它的工作時遍歷并選擇序列中的對象,而client程序猿不必知道或關心該集合序列底層的結構。
?????? UML類圖:
???????
???????? 角色:??????
??????? Iterator(迭代器):迭代器定義訪問和遍歷元素的接口
??????? ConcreteIterator(詳細迭代器):詳細迭代器實現迭代器接口,對該聚合遍歷時跟蹤當前位置
??????? Aggregate (聚合):聚合定義創建對應迭代器對象的接口(可選)
??????? ConcreteAggregate(詳細聚合):詳細聚合實現創建對應迭代器的接口,該操作返回ConcreteIterator的一個適當的實例(可選)
???????
???????? 核心代碼:
?????????
<?php /** * Created by PhpStorm. * User: Jiang * Date: 2015/6/8 * Time: 21:31 */ //抽象迭代器 abstract class IIterator { public abstract function First(); public abstract function Next(); public abstract function IsDone(); public abstract function CurrentItem(); } //詳細迭代器 class ConcreteIterator extends IIterator { private $aggre; private $current = 0; public function __construct(array $_aggre) { $this->aggre = $_aggre; } //返回第一個 public function First() { return $this->aggre[0]; } //返回下一個 public function Next() { $this->current++; if($this->current<count($this->aggre)) { return $this->aggre[$this->current]; } return false; } //返回是否IsDone public function IsDone() { return $this->current>=count($this->aggre)?
true:false; } //返回當前聚集對象 public function CurrentItem() { return $this->aggre[$this->current]; } }
????????? 調用client測試代碼:
?????????
header("Content-Type:text/html;charset=utf-8"); //--------------------------迭代器模式------------------- require_once "./Iterator/Iterator.php"; $iterator= new ConcreteIterator(array('周杰倫','王菲','周潤發')); $item = $iterator->First(); echo $item."<br/>"; while(!$iterator->IsDone()) {echo "{$iterator->CurrentItem()}:請買票。<br/>";$iterator->Next(); }???????? 使用場景:???
???????? 1.訪問一個聚合對象的內容而無需暴露它的內部表示
???????? 2.支持對聚合對象的多種遍歷
???????? 3.為遍歷不同的聚合結構提供一個統一的接口
?????? 歡迎關注我的視頻課程。地址例如以下。謝謝。
版權聲明:本文博主原創文章,博客,未經同意不得轉載。
總結
以上是生活随笔為你收集整理的PHP设计模式——迭代模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: repr
- 下一篇: putty network error: