ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Polymorphism | 37

instantiated using the subclasses, and each launched the same method,myMusic( ).


However, with each usage, even though all shared the same datatype (or supertype),


Polymorphism, each instance’s use of the method generates a unique outcome.


Looking at the program and your MP3 library, you may be thinking, “That’s not


nearly enough music categories.” What aboutR&B,Country,Alternative, Hip-Hop,


andCowboymusic? (Cowboy?) We couldn’t agree more. Go ahead and create new


subclasses using polymorphism to add all the categories you want. (This is not one of


those exercises where the answer is at the end of the chapter or the back of the book.


You’re on your own. Programmers don’t get polymorphism right without writing


their own code. See if you’ve got the right stuff.) By the way, notice that you can


make all the changes you want with polymorphism without having to change any of


the other classes. That’s the whole point of polymorphism.


Implementing Polymorphism with Interfaces


The ActionScript 3.0interfacestatement and structure is the other powerful tool for


polymorphism in both object-oriented programming and design patterns. Suppose


you’re building an e-business site. You have no idea how many new products the site


will have, but you know the site will have many different products that change regu-


larly. You’re going to need something that will handle a wide variety of products,


and a way of displaying them.


You know that you’ll need the following operations, but you’re not sure about the


details:



  • Description

  • Price

  • Product display


One way to set up an e-business site would be to create a class that has methods for


all three operations. However, suppose you find out that the client wants different


kinds of displays for the different products. She wants dynamically loaded video for


video products (e.g. TV sets), sound for sound products (e.g. MP3 players) and


graphic images for all other products. The operations for both description and price


methods are pretty standard, but the display method is going to have to be very flexi-


ble. That’s where polymorphism comes in. We could use an abstract class, but to


provide ever more flexibility just in case other unanticipated requirements crop up,


we’ll use an interface.


Example 1-32 through Example 1-36 make up the e-business application. The inter-


face,IBiz, contains the primary operations with unique signatures but not any


details. This will allow us to create the unique details we need as long as we keep all


the signatures the same.

Free download pdf