Iterator_迭代器模式_PHP语言描述
2019獨角獸企業重金招聘Python工程師標準>>>
感覺最近寫的這些設計模式的例子,在定義描述方面差很多,以后都會先寫一下用例設計模式的定義及簡單講解,在把例子附上,這樣的感覺更好些,也讓大家看得更清楚一些。
Iterator_迭代器模式的定義:
提供一種方法可以順序的訪問一個聚合對象中的集合,而不外露該對象的內部表示。
所謂的聚合是指一組對象的組合結構:比如數組,LIST,QUEUE等等(在PHP中得SPL庫中,有完善的各類高級數據結構以及Iterator接口及其實現已方便PHP的foreach循環訪問)。
Iterator_迭代器模式解決問題的思路:
仔細閱讀上面的定義,我們可以知道我們需要一個統一的方法來訪問各種實現不同的聚合對象。那么首先我們需要把這個統一的訪問方法抽象并定義出來,按照這個統一的訪問方式定義出來的接口在迭代器模式中對應的就是Iterator接口。
接下來就該考慮如何創建迭代器了,由于迭代器和相應的聚合對象緊密相關,因此應該讓具體的聚合對象來負責創建相應的迭代器。
Iterator(interface):迭代器接口,用于抽象定義訪問和遍歷元素的接口。
ConcreteIterator(class implements Iterator interface):具體的迭代器實現類,實現對聚合對象的遍歷,并跟蹤遍歷對象的各種索引及當前位置。
Aggregate(abstract class):聚合對象的抽象類,定義創建相應迭代器對象的接口。
ConcreteAggregate(class extends Aggregate):具體的聚合對象的實現類,實現創建相應的迭代器對象。
注:不同類型的聚合對象的實現類,需要實現不同的相應的迭代器類。
具體例子:
<?php/*** 迭代器接口,定義訪問和遍歷元素的操作 */interface IIterator{//移動到聚合對象的第一個元素位置public function first();//移動到聚合對象的下一個元素位置public function next();/*** 判斷是否已經移動到聚合對戲那個的最后一個位置* @return trun 表示移動到了聚合對象的最后一個位置* @return false 表示還沒有移動到聚合對象的最后一個位置*/public function isDone();/*** 取得迭代的當前元素* @return 返回迭代的當前元素*/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的工廠方法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();} ?>
轉載于:https://my.oschina.net/cniiliuqi/blog/64442
總結
以上是生活随笔為你收集整理的Iterator_迭代器模式_PHP语言描述的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 九把巨剑,为什么会从天而降?
- 下一篇: 让zabbix图像中文不再是乱码