Iterator pattern

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows SearchForElement to be used on any container that supports the required type of iterator.

Definition

The essence of the Iterator Factory method Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.".[1]

Language-specific implementation

Main article: Iterator

Some languages standardize syntax. C++ and Python are notable examples.

C++

C++ implements iterators with the semantics of pointers in that language. In C++, a class can overload all of the pointer operations, so an iterator can be implemented that acts more or less like a pointer, complete with dereference, increment, and decrement. This has the advantage that C++ algorithms such as std::sort can immediately be applied to plain old memory buffers, and that there is no new syntax to learn. However, it requires an "end" iterator to test for equality, rather than allowing an iterator to know that it has reached the end. In C++ language, we say that an iterator models the iterator concept.

C#

.NET Framework has special interfaces that support a simple iteration: System.Collections.IEnumerator over a non-generic collection and System.Collections.Generic.IEnumerator<T> over a generic collection.

C# statement foreach is designed to easily iterate through the collection that implements System.Collections.IEnumerator and/or System.Collections.Generic.IEnumerator<T> interface.

Example of using foreach statement:

var primes = new List<int>{ 2, 3, 5, 7, 11, 13, 17, 19};
long m = 1;
foreach (var p in primes)
    m *= p;

Java

Java has the Iterator interface.

As of Java 5, objects implementing the Iterable interface, which returns an Iterator from its only method, can be traversed using the enhanced for loop syntax.[2] The Collection interface from the Java collections framework extends Iterable.

Python

Python prescribes a syntax for iterators as part of the language itself, so that language keywords such as for work with what Python calls sequences. A sequence has an __iter__() method that returns an iterator object. The "iterator protocol" requires next() return the next element or raise a StopIteration exception upon reaching the end of the sequence. Iterators also provide an __iter__() method returning themselves so that they can also be iterated over e.g., using a for loop. Generators are available since 2.2.

In Python 3, next() was renamed __next__().[3]

PHP

PHP supports the iterator pattern via the Iterator interface, as part of the standard distribution.[4] Objects that implement the interface can be iterated over with the foreach language construct.

Example of patterns using PHP:

<?php

// BookIterator.php

namespace DesignPatterns;

class BookIterator implements \Iterator
{
    private $i_position = 0;
    private $booksCollection;

    public function __construct(BookCollection $booksCollection)
    {
        $this->booksCollection = $booksCollection;
    }

    public function current()
    {
        return $this->booksCollection->getTitle($this->i_position);
    }

    public function key()
    {
        return $this->i_position;
    }

    public function next()
    {
        $this->i_position++;
    }

    public function rewind()
    {
        $this->i_position = 0;
    }

    public function valid()
    {
        return !is_null($this->booksCollection->getTitle($this->i_position));
    }
}
<?php

// BookCollection.php

namespace DesignPatterns;

class BookCollection implements \IteratorAggregate
{
    private $a_titles = array();

    public function getIterator()
    {
        return new BookIterator($this);
    }

    public function addTitle($string)
    {
        $this->a_titles[] = $string;
    }

    public function getTitle($key)
    {
        if (isset($this->a_titles[$key])) {
            return $this->a_titles[$key];
        }
        return null;
    }

    public function is_empty()
    {
        return empty($a_titles);
    }
}
<?php

// index.php

require 'vendor/autoload.php';
use DesignPatterns\BookCollection;

$booksCollection = new BookCollection();
$booksCollection->addTitle('Design Patterns');
$booksCollection->addTitle('PHP7 is the best');
$booksCollection->addTitle('Laravel Rules');
$booksCollection->addTitle('DHH Rules');

foreach($booksCollection as $book){
    var_dump($book);
}

OUTPUT

string(15) "Design Patterns"
string(16) "PHP7 is the best"
string(13) "Laravel Rules"
string(9) "DHH Rules"

JavaScript

JavaScript, as part of ECMAScript 6, supports the iterator pattern with any object that provides a next() method, which returns an object with two specific properties: done and value. Here's an example that shows a reverse array iterator:

function reverseArrayIterator(array) {
    var index = array.length - 1;    
    return {
       next: () => 
          index >= 0 ? 
           {value: array[index--], done: false} : 
           {done: true}       
    }
}

const it = reverseArrayIterator(['three', 'two', 'one']);
console.log(it.next().value);  //-> 'one'
console.log(it.next().value);  //-> 'two'
console.log(it.next().value);  //-> 'three'
console.log(`Are you done? ${it.next().done}`);  //-> true

Most of the time, though, what you want is to provide Iterator[5] semantics on objects so that they can be iterated automatically via for...of loops. Some of JavaScript's built-in types such as Array, Map, or Set already define their own iteration behavior. You can achieve the same effect by defining an object's meta @@iterator method, also referred to by Symbol.iterator. This creates an Iterable object.

Here's an example of a range function that generates a list of values starting from start to end, exclusive. Notice how I can use a regular for loop to generate these numbers:

function range(start, end) {
  return {
    [Symbol.iterator]() { //#A
      return this;
    },
    next() {
      if(start < end) {
        return { value: start++, done:false }; //#B
      }
      return { done: true, value:end }; //#B
    }
  }
}

for(number of range(1, 5)) {
   console.log(number);   //-> 1, 2, 3, 4
}

I can also manipulate the iteration mechanism of built-in types, like strings.

let iter = ['I', 't', 'e', 'r', 'a', 't', 'o', 'r'][Symbol.iterator]();
iter.next().value; //-> I
iter.next().value; //-> t

See also

References

External links

The Wikibook Computer Science Design Patterns has a page on the topic of: Iterator implementations in various languages
This article is issued from Wikipedia - version of the Saturday, April 30, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.