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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Doing Composition<br />

To understand <strong>com</strong>position, we will start with a simple example. In the next sample<br />

application you’ll see that both inheritance and <strong>com</strong>position are used together. Each<br />

example will show one of the following relationships:<br />

• “Is a” relationship: object inherited<br />

• “Has a” relationship: object <strong>com</strong>position<br />

• “Uses a” relationship: one object used by another object (instantiated without<br />

inheritance or <strong>com</strong>position.)<br />

In the next section on delegation, we’ll look at these relationships. For now, though,<br />

each of the classes in the application made up of Examples 1-42 through 1-44 show<br />

each of these relationships. The <strong>com</strong>ments in the examples identify the type of relationship.<br />

First, we establish a base class to be the delegate.<br />

Example 1-42. BaseClass.as<br />

package<br />

{<br />

public class BaseClass<br />

{<br />

public function homeBase( )<br />

{<br />

trace("This is from the Base Class");<br />

}<br />

}<br />

}<br />

Composition includes a reference to another class in a class definition. Example 1-43<br />

shows how a class is set up to use <strong>com</strong>position. The line<br />

private var baseClass:BaseClass;<br />

keeps the reference to BaseClass in its class definition. That line is the basis of <strong>com</strong>position.<br />

The HasBase class now Has a BaseClass. In this particular implementation,<br />

the HasBase class creates an instance of BaseClass in its constructor. Finally, a public<br />

function, doBase( ), delegates the work back to BaseClass.<br />

Example 1-43. HasBase .as<br />

package<br />

{<br />

//Composition<br />

public class HasBase<br />

{<br />

private var baseClass:BaseClass;<br />

public function HasBase( )<br />

{<br />

baseClass=new BaseClass( );<br />

50 | Chapter 1: Object-Oriented Programming, <strong>Design</strong> <strong>Patterns</strong>, and <strong>ActionScript</strong> <strong>3.0</strong>

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

Saved successfully!

Ooh no, something went wrong!