ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Favor Composition | 51

Now, in Example 1-44, theHasBaseclass is used to delegate an operation back to


BaseClass. All this is done without having to inherit any ofBaseClass’ properties, but


HasBase does have aBaseClass. However,HasBase is not aBaseClass.


The advantages of using composition over inheritance are difficult to see in such a


small example. Later in the book, when examining the different design patterns, the


advantages will become clearer. However, when composition is used with a large


project, especially with a design pattern, its advantages begin to make even more sense.


You’ll really see why composition is preferred over inheritance when you have to make


changes to a large, complex program working with several other co-developers.


Using Delegation


Delegation is one of the most important concepts in working with design patterns


because by using it, composition can have the same power of reusability as inherit-


ance, with far greater flexibility. Because delegation typically works with inherit-


ance, any examination shouldnot be one where inheritance and delegation are


treated as mutually exclusive. Rather, we need to see how they differ and how they


are used in conjunction with one another—because that’s how they’re typically cast


in a design pattern.


}

public function doBase( )
{
baseClass.homeBase( );
}
}
}


Example 1-44. DoHasBase.as


package
{
//Executes the HasBase Composition class
import flash.display.Sprite


public class DoHasBase extends Sprite
{
private var hasBase:HasBase;
public function DoHasBase( )
{
hasBase=new HasBase( );
hasBase.doBase( );
}
}
}


Example 1-43. HasBase .as (continued)

Free download pdf