ActionScript 3.0 Design Patterns

(Chris Devlin) #1

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


The clearest way we’ve seen composition distinguished from inheritance is through


describing the relationship between components in an application. IfClassBis sub-


classed fromClassA,ClassBis described asbeing aClassA. However, ifClassBdele-


gates toClassA through composition, thenClassB can be said tohave aClassA.


You may have a class set up for loading SWF files in a desired configuration. You


want the functionality of loading the SWF files in that configuration, but you also


want to play audio using MP3 files. Using composition, you could simply create a


class that delegates each function to the appropriate classes. Figure 1-7 shows this


relationship:


In this situation, inheritance would not be too helpful. You could subclass one class


but not both. Of course you could instantiate an instance of each class in the third


class, or simply subclass one class and then create an instance of whichever class you


didn’t subclass. That would be a new class with an “is-a” and a “uses-a” different


class for the other functionality. A class is considered a “uses-a” when it creates an


instance of another class but does not hold a reference to it.


To understand and best use composition, you need to understand how delegation


really works, and to explain, you need to see it in a slightly more realistic example of


its use. The application will simulate a media application for playing and recording


media files using Flash and Flash Media Server 2 (FMS2). You can play either FLV or


MP3 files using FMS2. While you can record FLV files using FMS2, you can’t pub-


lish MP3 files by themselves. This application is designed for adding future features


and reducing dependencies at the same time.


If you are pretty sure that both the media server and your application will change,


then you’ll want to minimize dependencies by using composition and delegation. For


example, suppose that a future version of FMS2 changes, and you can record MP3


files directly. You’d only have to change theRecordAudioclass so that it would record


audio. By making that change, nothing else in the application would be affected.


Alternatively, suppose you have a holographic player that you want to add to the


mix. You can easily add another class that will play and/or record holographic


images without disturbing the rest of the application.


Figure 1-7. Delegating to different classes


Has a Loads
SWF files

Has a Loads
MP3 files

Loads
SWF files

Plays
MP3 files

delegates

delegates
Free download pdf