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

Chapter 1. Object-Oriented Programming, Design Patterns, and ActionScript 3.0

Let it be your constant method to look into the design of people's actions, and see what they would be at, as often as it is practicable; and to make this custom the more significant, practice it first upon yourself.

Marcus Aurelius

The life history of the individual is first and foremost an accommodation to the patterns and standards traditionally handed down in his community.

Ruth Benedict

At the lowest cognitive level, they are processes of experiencing, or, to speak more generally, processes of intuiting that grasp the object in the original.

Edmund Husserl

The Pleasure of Doing Something Well

The idea of design patterns is to take a set of patterns and solve recurrent problems. At the same time (even in the same breath), the patterns reflect good object-oriented programming (OOP) practices. So, we cannot separate OOP from design patterns, nor would we want to do so.

In answering the question of why bother with design patterns, we are really dealing with the question of why bother with OOP. The standard response to both design patterns and OOP often points to working with a team of programmers and speaking the same language. Further, it's easier to deal with the complexities involved with programming tasks requiring a division of labor for a large project using an object metaphor and practices.

In addition to coordinating large projects, programmers use both OOP and design patterns to deal with change. One key, important element, of design patterns is that they make changing a program much easier. The bigger a program and the more time you've spent developing it, the greater the consequences in making a change to that program. Like pulling a string in a sweater that unravels it, changing code in a program can have the same unraveling consequences. Design patterns and good OOP ease the task of making changes in complex programs, and reduce the changes or global problems.

Team coordination and application update and maintenance are reasons enough to learn design patterns. However, this is not the case if most programs you write are relatively short, you don't work with teams, and you don't worry about change. Then rewriting the short program is neither time-consuming nor difficult. What possible reason would you then have for learning design patterns?

Beside the fact that ActionScript 3.0 is based on ECMAScript and is not likely to have major changes with each new release of Flash or Flex as in the past, you have a far more personal reason for learning design patterns. Alexander Nakhimovsky and Tom Myers, in writing about using OOP with JavaScript (Wrox, 1998), point out the value in the pleasure derived from doing something well. Like any endeavor, whether it be skateboarding or building a house, people can find pleasure in doing a task well. By "doing something well," we do not mean an obsessive perfectionism—especially since perfectionism often leads to task paralysis. Rather, like any task that one can see an outcome and experience a process of accomplishment, when it's done right, you experience the craftsman's pleasure of the creative process and results.

Sequential and Procedural Programming

If you've never heard of sequential programming, that's the kind of programming you've most likely been doing. Most amateur programmers just write one statement after another, and any program that has the correct sequence of statements works just fine. However, as programs became more complex, programmers ran into an unruly jumble of code often called spaghetti programs. To remedy the jumble effect of sequential programming, programmers began organizing programs into a set of procedures and set of rules, and procedural programming was born. Instead of willy-nilly GOTO statements jumping all over a program, subroutines modularly defined program flow with appropriate GOSUB/RETURN procedures to keep everything tidy.

Note

The RETURN statements back then were different from what they are today. A RETURN meant to return to the position in a sequence of code where the GOSUB had originated. In ActionScript, a return statement means that an operation sends back information generated in the operation [the method or procedure].

Also, from procedural programming came the concept of scope so that variables in functions and subroutines could be reused and one procedure would not contaminate another.

The great majority of programming languages today are considered procedural in that they have the concepts and syntax that support it. The different versions of BASIC are procedural, as are languages like ColdFusion, PHP and Perl. However, C++ is a procedural language, as is ECMAScript (ActionScript 3.0) and Ada, languages many consider object-oriented. Languages like Java are considered true OOP languages. Without going into a lot of detail, the reason Java is considered a true OOP language and the others are not is because the only kind of procedure in Java is a class method. Its structure forces procedures to be class methods, and doesn't allow other procedures to operate outside the class structure.

Note

You might be surprised at how heated a discussion can get when it comes to a language being an OOP language or not. Two versions of OOP criteria exist. One is fairly inclusive and allows any language with certain features that can generate OOP code to be considered OOP. (ActionScript 3.0 is among those.) The other version has a restrictive criterion that includes those languages that only allow methods as procedures to be admitted to the exclusive club of OOP languages. Both versions have valid points. However, we will sidestep the issue by not taking a position, but note that both sides agree that you can create good OOP code with a procedural language.

To make a long story short, this does not mean that the other languages are unable to generate true OOP programs. Well before Java was even available, developers were creating OOP programs. Some languages, especially those with the ability to use class structures and override methods, such as ActionScript 3.0, are more OOP friendly than others. As ActionScript has matured from a few statements to a true ECMAScript language, it has become more OOP friendly.

Transition to OOP

Changing from sequential or procedural programming to OOP programming is more than picking up a language that gives you little choice in the matter, as is the case with Java. However, certain changes in a language can make it more amenable to OOP, even if it's not considered a true OOP language by some criterion. In the following sections, some new features in Flash CS3 provide a summary of relevant changes to the way ActionScript is used.

MovieClip and Button scripts

For the ActionScript veterans whose introduction to programming was writing little sequential scripts or procedures using the on statements associated with MovieClip or Button objects, you're probably aware that the latest version of Flash doesn't allow script embedded in either.

Note

Built-in State Machines

While most programmers welcomed the demise of movie clip and button embedded scripts, one astute programmer observed that Flash used to have built-in state machines. Jonathan Kaye, PhD, co-author of Flash MX for Interactive Simulation: How to Construct and Use Device Simulations (Delmar Learning, 2002), noted that the button and movie clip scripts often served to create state machines. Each button or movie clip could serve as an encapsulated, context-sensitive trigger for changing state. (See how design patterns deal with State Machine in Chapter 10.)

In general, the demise of movie clip and button scripts is seen as a boon to better programming, especially OOP programming. Keeping track of the isolated button and movie clip codes could be a headache, even with relatively small applications. For structuring larger programs, where OOP and Design Patterns are most useful, having movie clips and buttons floating around with their own code moves the problem from the realm of headache to nightmare. So, for learning design patterns, be glad you don't even have to think about little scripts isolated in movie clips and buttons.

Timeline scripts

Another kind of scripting you'll be seeing less of in Flash are those embedded in your Timeline. For the most part, placing scripts in the Timeline probably left a lot to be desired in the first place, but worked out to be a convenient location. In ActionScript 2.0, you were able to place a script in a class and call it from a script embedded in the Timeline, and so all that the Timeline code was really used for was to call a class that would launch a script in an ActionScript file (.as). That being the case, the Flash CS3 .fla file has a little window where you can add the name of the class to call. (See the next section.) So, if all you want to do is to call a program and compile it into an SWF file, you no longer need to use the Timeline for your code at all.

However, Flash CS3 doesn't do away with code in the Timeline. You can still use it, but in this book, we use it selectively only with movie clips that are called from a class outside the movie clip or button class. (See the section "Movie Clip and Button Classes.")

Document class

You won't be placing much, if any, code in the Timeline using ActionScript 3.0. Rather than using an object with a Timeline script, you can now compile your .as files by entering the name of the class name you want to launch your application. Figure 1-1 shows how to use the Document class window in the Properties panel to enter the name of the class you want to launch:

Document class window

Figure 1-1. Document class window

You can still use the Timeline, but unless there's a good reason to do so, there's no need. Most of the examples in this book use the Sprite object instead of the MovieClip class. A Sprite object has no Timeline, but a MovieClip class does. So using Sprite objects save a bit of extra weight that the Timeline has.

Movie clip and button classes

In Flash CS3, MovieClip and Button objects you create using the Symbol dialog box and store in the Library can be made available to work with ActionScript 3.0. Unlike ActionScript 2.0 where MovieClip and Button symbols could be associated with a class, with Flash CS3, they can be made into classes themselves. The object's name entered into the Name window when the symbols are created becomes the class name for the object. (In past versions, references to a movie clip are made through an instance name. You can still make those references can still be made, but in a different context.)

The advantage of this new procedure is that the symbol objects can be instantiated just like any other class through the code, as long as the symbols are in the Library. You don't have to place them on the stage. They can be dynamically instantiated and placed into a display array just like a dynamically generated object. Further, objects contained within the MovieClip or Button can be addressed as a property just like any other class.

While this book is in no way an introduction to Flash CS3, walking through one example of this new way of creating a class with movie clips and buttons may be useful to those new to Flash and experienced users alike. The following steps walk you through this new feature:

  1. Open a new Flash document and save it as rocket.fla.

  2. Select Insert→New Symbol from the menu bar to open the Create New Symbol Dialog box. Enter "Rocket" in the Name window, and Click OK to enter the Symbol Edit Mode.

  3. In the Symbol Edit Mode, draw a rocket on the stage with the dimensions W=89, H=14, as shown in Figure 1-2. Once finished, position the drawing at X=0, Y=0. Click the Scene 1 icon to exit the Symbol Edit Mode.

    Rocket drawing

    Figure 1-2. Rocket drawing

  4. Select Insert→New Symbol from the menu bar to open the Create New Symbol Dialog box. Enter "FireRocket" in the Name window, select Movie clip as Type, and click the Export for ActionScript checkbox. Once you've clicked the checkbox, Figure 1-3 shows what the dialog box looks like. Notice that the Base class is flash.display.MovieClip. The base class is the reference to the package required for ActionScript to display a MovieClip object. Click OK to enter the Symbol Edit Mode

    Setting a MovieClip class

    Figure 1-3. Setting a MovieClip class

  5. Drag a copy of the Rocket movie clip from the Library to the center of the stage. Move the center point of the movie clip to the rear of the rocket and position it at X=0, Y=0.

  6. Click on Frame 40 of the Timeline and press F5 to create 40 frames. Click Frame 40 again and press F6 to insert a keyframe. Click on the keyframe in frame 40 and move the rocket to X=400, Y=0.

  7. Click on the first keyframe, and, in the tween drop-down menu in the Properties inspector, select Motion. You should now see a blue arrow in the Timeline. Move the playhead from left to right to make sure that the motion tween is working right. Figure 1-4 shows what you should see:

    Rocket in motion tween

    Figure 1-4. Rocket in motion tween

  8. Open the Actions panel. Click on a blank area of the stage to make sure you don't have any objects selected, and then click on Frame 1. In the Actions panel, type in the stop() statement. Save the Rocket.fla file.

  9. Open a new ActionScript file and save it as TestRocket.as in the same folder as the Rocket.fla file. Enter the script in Example 1-1 in the TestRocket.as file, and save the file once again:

    Example 1-1. TestRocket.as

    package
    {
        import flash.display.Sprite;
    
        public class TestRocket extends Sprite
        {
            private var fireRocket:FireRocket;
            public function TestRocket()
            {
                fireRocket=new FireRocket();
                fireRocket.x=50;
                fireRocket.y=100;
                addChild(fireRocket);
                fireRocket.gotoAndPlay(2);
            }
        }
    }

  10. Finally, open the Rocket.fla file, and in the Document class window in the Properties panel, type in TestRocket and save the file. Then test the movie by pressing Ctrl + Enter (Command + Return on the Mac). You should see the rocket move from left to right across the screen and then return to its original position.

Using Flash in a more or less traditional manner to create movie clips is still an important part of using ActionScript, but it has changed. You can no longer attach a class to a movie clip as was the case in previous versions. However, in creating applications using design patterns, you can still integrate different aspects created in the Flash IDE. So while ActionScript 3.0 has made the leap to a true ECMAScript language, it has not abandoned its roots in animated graphics.

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