Composite elements also implement the element interface, but unlike leaf elements, you can add child elements to composites. In our file system example, directories are composite elements. The following is a Directory class that represents a file system directory in our file system example. Notice that the class extends the abstract FileSystemItem class. Because the abstract class defers the implementation of iterator(), addItem(), and removeItem() to subclasses, the Directory class must override these methods. package com.peachpit.aas3wdp.compositeexample.data { import com.peachpit.aas3wdp.iterators.IIterator; import com.peachpit.aas3wdp.iterators.ArrayIterator; public class Directory extends FileSystemItem { // The array of child elements private var _items:Array; public function Directory() { _items = new Array(); } override public function addItem(item:IFileSystemItem):void { _items.push(item); } override public function removeItem(item:IFileSystemItem):void { var i:uint; // Loop through all the child elements. for(i = 0; i < _items.length; i++) { // If one of the elements matches the // parameter remove it from the array. if(_items[i] == item) { _items.splice(i, 1); break; } } } override public function iterator():IIterator { // See the "Iterator Pattern" chapter for details on // ArrayIterator return new ArrayIterator(_items); } } } The Directory class implementation is fairly simple. It must override addItem() to append the element to the _items array. The class overrides removeItem() to remove the specified item by looping through all the elements of the _items array until it finds the matching element. And the class overrides iterator() to return an ArrayIterator instance. |