github地址:https://github.com/ZQCard/design_pattern
/** * 迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。 * 这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。迭代器模式属于行为型模式。 */
(1)Iterator.class.php(接口)
<?php namespace Iterator; interface Iterator { public function First(); public function Next(); public function IsDone(); public function CurrentItem(); }
(2) ConcreteIteratior.class.php
<?php namespace Iterator; class ConcreteIterator implements Iterator{ private $_users; private $_current = 0; public function __construct(array $users) { $this->_users = $users; } public function First() { return $this->_users[0]; } //返回下一个 public function Next() { $this->_current++; if($this->_current<count($this->_users)) { return $this->_users[$this->_current]; } return false; } //返回是否IsDone public function IsDone() { return $this->_current>=count($this->_users)?true:false; } //返回当前聚集对象 public function CurrentItem() { return $this->_users[$this->_current]; } }
(3)iterator.php (客户端)
<?php spl_autoload_register(function ($className){ $className = str_replace('\\','/',$className); include $className.".class.php"; }); use Iterator\ConcreteIterator; $iterator= new ConcreteIterator(array('周杰伦','王菲','周润发')); $item = $iterator->First(); echo $item."<br/>"; while(!$iterator->IsDone()) { echo "{$iterator->CurrentItem()}:请买票!<br/>"; $iterator->Next(); }