ActionScript 3.0 Design Patterns

(Chris Devlin) #1

50 | Chapter 1: Object-Oriented Programming, Design Patterns, and ActionScript 3.0


Doing Composition


To understand composition, we will start with a simple example. In the next sample


application you’ll see that both inheritance and composition are used together. Each


example will show one of the following relationships:



  • “Is a” relationship: object inherited

  • “Has a” relationship: object composition

  • “Uses a” relationship: one object used by another object (instantiated without
    inheritance or composition.)


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


each of the classes in the application made up of Examples 1-42 through 1-44 show


each of these relationships. The comments in the examples identify the type of rela-


tionship. First, we establish a base class to be the delegate.


Composition includes a reference to another class in a class definition. Example 1-43


shows how a class is set up to use composition. The line


private var baseClass:BaseClass;

keeps the reference toBaseClassin its class definition. That line is the basis of com-


position. TheHasBaseclass nowHas aBaseClass. In this particular implementation,


theHasBaseclass creates an instance ofBaseClassin its constructor. Finally, a public


function,doBase( ), delegates the work back toBaseClass.


Example 1-42. BaseClass.as


package
{
public class BaseClass
{
public function homeBase( )
{
trace("This is from the Base Class");
}
}
}


Example 1-43. HasBase .as


package
{
//Composition
public class HasBase
{
private var baseClass:BaseClass;


public function HasBase( )
{
baseClass=new BaseClass( );

Free download pdf