Using Null Iterators


One special iterator type is the null iterator. The null iterator enables you to build classes that adhere to an interface (they are iterable) but that don't actually have any collection data. The classic case for null iterators is the leaf element of a composite object (as discussed in Chapter 8, "Composite Pattern"). In such cases, it's necessary that the leaf elements (those containing no collection data) and the composite elements (those that do contain collection data) implement the same interface and be treated in the same way. For recursive traversal purposes, it's necessary that the interface provide access to an iterator for both composite and leaf elements. One option is to return null for the leaf element iterator. However, doing so presents a special case that you must detectnamely, you must add if statements to test whether the iterator is null or not before calling the methods such as hasNext() and next(). A more elegant solution is to use a special type of iterator that always returns false for hasNext() and returns null for next(). That special-case iterator is a null iterator as defined in the following code:

package com.peachpit.aas3wdp.iterators {    public class NullIterator implements IIterator {                 public function NullIterator() {}       public function hasNext():Boolean {          return false;       }         public function next():Object {          return null;       }                 public function reset():void {       }             } }


We'll see an example of how to use this iterator type in the next chapter.




Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net