Iterator mode:
The iterator pattern is the mature pattern of traversing the collection, the key to the iterator pattern is to pass the task of iterating over the collection to an object called an iterator, which traverses and selects the objects in the sequence as it works, while the client programmer does not have to know or care about the underlying structure of the collection sequence.
Role:
Iterator (iterator): An iterator that defines an interface for accessing and traversing elements
Concreteiterator (Specific iterator): The specific iterator implements the iterator interface, which tracks the current position for the aggregation over duration
Aggregate (Aggregation): aggregation defines an interface for creating an appropriate iterator object (optional)
Concreteaggregate (Specific aggregation): A concrete aggregation implements an interface that creates an appropriate iterator that returns an appropriate instance of Concreteiterator (optional)
UML Class Diagrams:
Applicability:
Accesses the contents of an aggregated object without exposing its internal representation.
Supports multiple traversal of an aggregated object.
Provides a unified interface for traversing different aggregation structures (that is, support for polymorphic iterations).
Code implementation:
<?PHPHeader("content-type:text/html; Charset=utf-8 ");//iterator interface, take care not to use iterator naming, which is a built-in interfaceAbstract classiiterator{Abstract functionFirstvalue ();//get the first element in an aggregation Abstract functionNextValue ();//gets the next element of the aggregation Abstract functionCurrentValue ();//gets the current element in the aggregation Abstract functionIsfinished ();//determine if the aggregation has been traversed}//Specific iteratorsclassConcreteiteratorextendsiiterator{Private $aggr;//Specific aggregation elements Private $currentKey= 0; function__construct ($aggr){ $this->aggr =$aggr; } //gets the first element functionfirstvalue () {return $this->aggr[0]; } //gets the next element functionNextValue () {$this->currentkey++; if($this->currentkey<Count($this-Aggr)) { return $this->aggr[$this-Currentkey]; } return false; } //gets the current element functionCurrentValue () {return $this->aggr[$this-Currentkey]; } //whether the current aggregation has traversed completion functionisfinished () {return $this->currentkey>=Count($this->AGGR)?true:false; }}//Test$iterator=NewConcreteiterator (Array("Zhang San", "John Doe", "Harry"));Echo $iterator-firstvalue ();Echo $iterator-NextValue ();Echo $iterator-CurrentValue ();?>
Iterator Mode and PHP implementation