標籤:io os java ar sp cti on c ad
不多說,對於PHP的新手來說,學習到了。
<?php/** * 迭代器的公用介面 */interface NewIterator{ public function hasNext(); public function Next();}/** * 書目的迭代器,實現NewIterator介面 */class BookIterator implements NewIterator { private $array = array();//記錄整個內容 private $num = 0;//記錄索引 public function __construct($_string){ //因為在我的例子裡需要這樣處理。 if (is_array($_string)){ $this->array = $_string; }else{ $this->array = explode("|",$_string); } } public function next(){ //記錄下一項的內容 $arrayA = $this->array[$this->num]; //索引增加1 $this->num = $this->num + 1; return $arrayA; } public function hasNext(){ if($this->num >= count($this->array) || $this->array[$this->num] == null){ return false; }else{ return true; } }}/** * 數目是用數組儲存的 */class BookA{ private $bookarray = array(); public function __construct(){ $this->addItem("深入淺出設計模式"); $this->addItem("think in java"); $this->addItem("php手冊"); } public function addItem($_string){ $this->bookarray[]=$_string; } //這裡不再返回一個數組。而是一個真正的對象。數組被傳遞到了迭代器中。實現和書目調用的解耦 public function getIterator(){ return new BookIterator($this->bookarray); }}/** * 書目都是用字串儲存的 */class BookB{ private $bookindex=""; public function __construct(){ $this->addItem("深入淺出設計模式"); $this->addItem("PHP"); $this->addItem("think in java"); } public function addItem($_string){ $this->bookindex.="|".$_string; } public function getIterator(){ return new BookIterator(trim($this->bookindex,"|"));//附帶的處理而已 }}/** * 輸出兩個書店的書目// *///require "NewIterator.php";//require ‘BookA.php‘;//require ‘BookB.php‘;//require "BookIterator.php"; class BookList{ private $bookarray; private $bookstring; public function __construct(BookA $_booka,BookB $_bookb){ $this->bookarray = $_booka; $this->bookstring = $_bookb; //改裝成了只記錄對象引用; } public function Menu(){ $bookaiterator = $this->bookarray->getIterator(); echo "書店A的書目:"."</br>"; $this->toString($bookaiterator); echo "</br>"; $bookbiterator = $this->bookstring->getIterator(); echo "書店B的書目:"."</br>"; $this->toString($bookbiterator); } public function toString(NewIterator $_iterator){ while ($_iterator->hasNext()){ echo $_iterator->Next()."</br>"; } }}$booka=new BookA();$bookb=new BookB();$a = new BookList($booka,$bookb);$a->Menu();?>
PHP實現迭代器