O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Example: Music Playlists

Have you created music playlists in your favorite digital music jukebox? If so, have you taken the next step and embedded playlists inside other playlists to create ever larger playlists? This is a perfect application to implement a composite pattern. A library of digital music contains songs and playlists. A song is a primitive object, while a playlist is a composite object that contains a collection of songs. Let's first create the component class for our playlist example application.

The Component.as file (Example 6-1) contains the Component abstract class that defines the interface for both songs and playlists. The Song.as file (Example 6-10) contains the Song class, and the Playlist.as file (Example 6-9) contains the Playlist class. Both Song and Playlist classes extend the Component class and provide necessary implementations.

Example 6-8. Component.as

package
{
    import flash.errors.IllegalOperationError;

    // ABSTRACT Class (should be subclassed and not instantiated)
    public class Component
    {
        public function add(c:Component):void
        {
            throw new IllegalOperationError
                ("add operation not supported");
        }

        public function remove(c:Component):void
        {
            throw new IllegalOperationError
                 ("remove operation not supported");
        }

        public function getChild(n:int):Component
        {
            throw new IllegalOperationError
                 ("getChild operation not supported");
            return null;
        }

        // ABSTRACT Method (must be overridden in a subclass)
        public function play():void {}
    }
}

The Component class defines the abstract ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required