Iterator pattern: The iterator pattern is a mature pattern for traversing a collection. The key to the iterator pattern is to hand over the task of traversing the collection to an object called an iterator. Its job is to traverse and select objects in the sequence, and The client programmer does not need to know or care about the underlying structure of the collection sequence.
UML class diagram:
Character:
Iterator: Iterator defines the interface for accessing and traversing elements
ConcreteIterator: A concrete iterator implements the iterator interface and tracks the current position when traversing the aggregate
Aggregate: Aggregation definition creates an interface for corresponding iterator objects (optional)
ConcreteAggregate (concrete aggregation): A concrete aggregate implements the interface that creates the corresponding iterator. This operation returns an appropriate instance of ConcreteIterator (optional)
Core code:
<!--?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]; } }</count($this->
header(Content-Type:text/html;charset=utf-8); //--------------------------迭代器模式------------------- require_once ./Iterator/Iterator.php; $iterator= new ConcreteIterator(array('周杰伦','王菲','周润发')); $item = $iterator->First(); echo $item. ; while(!$iterator->IsDone()) { echo {$iterator->CurrentItem()}:请买票! ; $iterator->Next(); }
1. Access the contents of an aggregate object without exposing its internal representation
2. Supports multiple traversals of aggregate objects
3. Provide a unified interface for traversing different aggregate structures
Welcome to follow my video course, the address is as follows, thank you.
PHP object-oriented design patterns