Jump to content

Iterator pattern

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Andy Dingley (talk | contribs) at 20:17, 5 May 2015 (Reverted 1 edit by 91.159.53.89 (talk): Rv self-promotional spam that doesn't offer anything to meet WP:EL. (TW)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

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.

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:

interface IIterator {
    /*
     * @param void
     * @return Boolean
     */
    public function hasNext();
	
    /*
     * @param void
     * @return String
     */
    public function next();
}

interface IContainer {
    /*
     * @param void
     * @return IInterator
     */
    public function createIterator();
}

class BooksCollection implements IContainer {
    private $a_titles = array();
	
    /*
     * @param void
     * @return IIterator
     */
    public function createIterator()
    {
        return new BookIterator($this);
    }

    /*
     * @param string
     * @return void
     */
    public function setTitle($string)
    {
        $this->a_titles[] = $string;
    }
	
    /*
     * @param void
     * @return Array
     */
    public function getTitles(){
        return $this->a_titles;
    }
}

class BookIterator implements IIterator {
    private $i_position = 0;
    private $booksCollection;
	
    function __construct(BooksCollection $booksCollection)
    {
        $this->booksCollection = $booksCollection;
    }
	
    /*
     * @param void
     * @return Boolean
     */
    public function hasNext()
    {
        if ($this->i_position < count($this->booksCollection->getTitles())) {
            return true;
        }
        return false;
    }
	
    /*
     * @param void
     * @return String
     */
    public function next()
    {
        $m_titles = $this->booksCollection->getTitles();
		
        if ($this->hasNext()) {
            return $m_titles[$this->i_position++];
        } else {
            return null;
        }
    }
}

class Tester {
    static function Main() {
        $booksCollection = new BooksCollection();
		
        $booksCollection->setTitle("Design Patterns");
        $booksCollection->setTitle("1");
        $booksCollection->setTitle("2");
        $booksCollection->setTitle("3");
		
        $iterator = $booksCollection->createIterator();
        while ($iterator->hasNext()) {
            echo $iterator->next() . '<br />';
        }
    }
}

Tester::Main();

See also

References

  1. ^ Gang Of Four
  2. ^ "An enhanced for loop for the Java™ Programming Language". Retrieved 25 June 2013.
  3. ^ "Python v2.7.1 documentation: The Python Standard Library: 5. Built-in Types". Retrieved 2 May 2011.
  4. ^ "PHP: Iterator". Retrieved 23 June 2013.