Un ejemplo en PHP - El patrón Iterator

Hemos visto la interfaz **"Iterator" ** que nos permitía recorrer un objeto, un array o incluso un directorio de esta forma:

<?php
   $obj = new ArrayObject(array(1,2,3));
   $it = $obj->getIterator();
   while( $it->valid() ) {
      echo $it->key() . "=" . $it->current() . "\n";
      $it->next();
   }
?>

Ventaja fundamental: el bucle siempre será igual sea un objeto, un array, un directorio. Buena idea, ¿no? Pero ¿es original de PHP? No es ni más ni menos que el patrón Iterator (casualmente se llama igual y todo...).

interface Iterator
{
   // Returns the current value
   function current();
   // Returns the current key
   function key();
   // Moves the internal pointer to the next element function
   next();
   // Moves the internal pointer to the first element
   function rewind();
   // If the current element is valid (boolean)
   function valid();
}

Más información en esta url:http://en.wikipedia.org/w/index.php?title=Iterator_ pattern&oldid=129779432

El patrón **Iterator** (según el GoF*) proporciona una forma consistente de recorrer los items de una colección que es independiente de los datos que contiene dicha colección.

El **GoF** define también los métodos que debería tener, entre los que se encuentra next e isDone (isValid de PHP)

results matching ""

    No results matching ""