ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Favor Composition | 49

In reviewing how the process works, first, theshowTimeinstance is typed to the inter-


face,IVid. Next,showTimeinstantiates theVidPlayerclass that has all the details for


playing the video. By doing so, it inherits theSpriteclass as well as theIVidinter-


face. Then theshowTimeclient plays the video using theplayVid( )method. Finally,


when theshowTimeinstance is added to the display list with theaddChildstatement, it


is added as both the child of theVidPlayerclass and theDisplayObjectclass by using


thedisplayObjectgetter. Because the getter,displayObject, is included in the dis-


play list, you willnot get the following error:


1067: Implicit coercion of a value of type IVid to an unrelated type
flash.display:DisplayObject.

IVidappears in the error because the instance was typed to the interface instead of


the implementation. By slipping in theDisplayObjecttyped getter method, we avoid


the error.


Favor Composition


Throughout this chapter, we have discussed the principle of programming to the


interface instead of the implementation. The second principle of object-oriented


design posited by Gamma, Helm, Johnson and Vlissdes (GoF) is:Favor object com-


position over class inheritance.


To understand this second key principle, we need to understand exactly whatcom-


positionmeans, and its advantages over inheritance. After all, the principle is essen-


tially stating that your programs will be better using composition than inheritance.


Does this mean to abandon inheritance? After all, inheritance is one key concept in


object-oriented programming. Actually, what GoF discuss is that most programmers


rely too heavily on inheritance, and need to use it more in conjunction with composi-


tion. Most programmers create new objects from old objects using inheritance, and,


through composition, the old and new objects can be used together.


The best way to understand composition is to see it in the context of its use. In this


book, both the State and Strategy patterns are built using composition, and they


depend on delegation. In the State design pattern, an object delegates requests to an


object representing the current state in an application. In the Strategy design pat-


tern, specific requests are delegated to objects representing strategies (algorithms) for


solving problems. The great advantage of both these design patterns is that they are


flexible and not bogged down in inflexible dependencies.

Free download pdf