Understanding Leaf Elements


Leaf elements are the terminating elements in the Composite pattern. Leaf elements can be placed in composite elements, but composite elements cannot be placed in leaf elements. In terms of our file system example, files are leaf elementsyou can place files in directories, but you cannot place directories in files.

Leaf elements must implement the same interface as composite elements for the pattern to work. This approach might seem odd at first because the element interface always allows for adding and removing elements, yet a leaf element cannot contain elements. In the Composite pattern, the leaf element does include the methods to add, remove, and access elements to satisfy the requirements of the interface, yet the implementation does not allow you to actually add, remove, or access elements. The following is the implementation for a File class as part of our file system example. Notice that it inherits from the abstract FileSystemItem class so that it doesn't need to implement most of the required methods (it inherits the implementations from its superclass). In particular, it doesn't have to override addItem() or removeItem() because the superclass implementations do nothing, which is exactly what we want the leaf class implementation to do. Although the File class does not need to override iterator(), to simplify working with File objects in the Composite pattern, we'll override iterator() so that it returns a NullIterator instance, as shown here:

package com.peachpit.aas3wdp.compositeexample.data {    import com.peachpit.aas3wdp.iterators.IIterator;    import com.peachpit.aas3wdp.iterators.NullIterator;      public class File extends FileSystemItem {                 public function File() {       }       override public function iterator():IIterator {          return new NullIterator();       }    } }


We talked about the NullIterator type in Chapter 7. Although the File implementation of iterator() could simply return null, it's slightly more elegant to return a NullIterator object. The reason is that if iterator() returns null, you might have to test for null values when using File objects. Yet if the method returns a NullIterator object, you can use the return value interchangeably with the return value from a composite object. Because a NullIterator object always returns false for hasNext(), it should allow a leaf object to work just like a composite object without ever actually iterating over child elements.




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