10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Executing the following statements accesses the third child of the second child of the<br />

root node; which is leaf 5. The parent of leaf 5 is the second child of the root node<br />

(see Figure 6-4).<br />

var leaf5:Component = root.getChild(2).getChild(3);<br />

var leaf5Parent:Composite = l5.getParent( );<br />

Calling the operation( ) on the parent of leaf 5 should give the following output.<br />

<strong>com</strong>posite 2<br />

leaf 3<br />

leaf 4<br />

leaf 5<br />

Implementing the remove method<br />

The primary concern with removing nodes has to do with removing all references to<br />

deleted objects so that the garbage collector can recover the memory they used. For<br />

example, before removing a <strong>com</strong>posite node, all its child nodes need to be deleted. If<br />

one of the child nodes is itself a <strong>com</strong>posite, then the remove method should recursively<br />

delete its children as well. Therefore, the remove method will work similar to<br />

the operation( ) method.<br />

From the previous scenario, it is evident that we need to treat leaf nodes and <strong>com</strong>posite<br />

nodes differently when deleting them. Therefore, it’s useful to declare a<br />

getComposite( ) method in the Component class to return the <strong>com</strong>posite object if it is<br />

indeed a <strong>com</strong>posite, and null if not. The default behavior would be to return null.<br />

The following method would be defined with its default implementation in the<br />

Component class.<br />

internal function getComposite( ):Composite<br />

{<br />

return null;<br />

}<br />

The Composite class would override this method and return the actual <strong>com</strong>posite<br />

object.<br />

override internal function getComposite( ):Composite<br />

{<br />

return this;<br />

}<br />

In addition, the parent references of <strong>com</strong>ponents should be removed before <strong>com</strong>ponents<br />

can be removed. The following method to remove the parent reference should<br />

be defined and implemented in the Component class.<br />

internal function removeParentRef( ):void<br />

{<br />

this.parentNode = null;<br />

}<br />

Minimalist Example of a Composite Pattern | 213

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!