ActionScript 3.0 Design Patterns Free ebook download

  www.dbeBooks.com - An Ebook Library

  ActionScript 3.0 Design Patterns

Other resources from O’Reilly

  Related titles Essential ActionScript 3.0 Learning JavaScript Dynamic HTML: The Programming Atlas Definitive Reference

  Head Rush Ajax Ajax on Java Rails Cookbook Ajax on Rails oreilly.com is more than a complete catalog of O’Reilly books. oreilly.com

  You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new platforms, pro- gramming languages, and operating systems.

  

Conferences O’Reilly brings diverse innovators together to nurture the ideas

that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit con- ferences.oreilly.com for our upcoming events.

  Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim-

ply flip to the page you need. Try it today for free.

  ActionScript 3.0 Design Patterns William B. Sanders and Chandima Cumaranatunge

  ActionScript 3.0 Design Patterns by William B. Sanders and Chandima Cumaranatunge Copyright © 2007 O’Reilly Media, Inc. All rights reserved.

  Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions

). For more information, contact our corporate/institutional sales department: (800) 998-9938 or .

  Steve Weiss John Bickelhaupt Editor: Indexer:

  Robyn G. Thomas Karen Montgomery Developmental Editor: Cover Designer:

  Philip Dangler David Futato Production Editor: Interior Designer:

  Sohaila Abdulali Robert Romano and Jessamyn Read Copyeditor: Illustrators: Printing History: July 20007: First Edition.

  

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of

O’Reilly Media, Inc. ActionScript 3.0 Design Patterns, the image of a rosy feather starfish, and related

trade dress are trademarks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as

trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a

trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

  ™ This book uses RepKover , a durable and flexible lay-flat binding.

  ISBN-10: 0-596-52846-9

  ISBN-13: 978-0-59652846-1 [M]

  

Bill would like to dedicate this to the new kids on

the block, Ricky and Olivia.

Chandima would like to dedicate this book to his

parents, Gaya and Lakshmie.

Table of Contents

  

  

  

  

  

  

  

  

  65

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

  

  

  

  

  

  

  

  

  

  3

   . . . . .

  

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

  

  

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

  

  

  

  

  

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

  

  

  

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427

  

  

  

   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398

  

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

499

  1 Preface

  As ActionScript has evolved from a few statements in Flash to a full-fledged Internet programming language in the latest release of Flash and Flex, we have the ability to implement sophisticated designs developed for languages using object-oriented pro- gramming (OOP). ActionScript 3.0 heralds a new era in Flash and Flexprogram- ming because it implements the ECMAScript standard for Internet languages. Many

  TM

  features found in languages such as C++ and Java are now available in Action- Script 3.0. Along with more sophisticated features in ActionScript 3.0 come more sophisticated ways of programming and thinking about programming. Most readers of this book will be familiar with OOP to some degree, and like the step from sequential or proce- dural programming to OOP, the step to design pattern programming is a step up for OOP programmers. We felt that because ActionScript 3.0 had arrived at a point where more complexand challenging programming structures can be developed, Flash and Flexprogrammers needed to understand programming techniques to cope with these structures. By understanding design pattern programming, you will be able to write better OOP code, and reuse that code in other programs. The better paying positions in the pro- gramming field favor those developers who can work with team development, and the sophisticated structures that design patterns and OOP were developed to han- dle. At the same time that you gain proficiency in programming more complexappli- cations, design patterns actually make programming easier. In large and complex applications, programmers have the most difficulty with poor planning and awk- ward design structures. Design patterns not only provide solutions for common chal- lenges, but also focus on maintenance and change. The vocabulary of design patterns is equally important because with it, you can become part of the developer commu- nity that communicates clearly in the language of design patterns.

Who This Book Is For We wanted to develop a book for intermediate to advanced ActionScript 3.0 users

  Unlike some languages, such as Java, where the readers are likely to have computer science or computer engineering degrees, most ActionScript 3.0 users are likely to have learned ActionScript in developmental stages using Flash. As a result, their backgrounds are far more varied, and the programming base less definite. We’re sure that a number of ActionScript programmers have computer science or related back- grounds, and much of the introductory materials in the first chapter will be redun- dant. Likewise, we’re certain that some readers on the lower end of the intermediate level are learning object-oriented programming at the same time that they’re trying to pick up design patterns; they may have little or no formal training in programming. Given the range of ActionScript programming backgrounds, we’re bound to be too difficult for some and too simplistic for others. However, this book’s overall goal is to explain how to use different design patterns. We targeted whom we considered intermediate level ActionScript developers. We’ve provided everything the intermedi- ate level developer will need to move to the advanced level. For the advanced user, we provide explanations and examples of how to use design patterns with Action- Script 3.0.

How This Book Is Organized

  The book’s organization reflects the topic organization found in Design Patterns Ele-

  

ments of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph

Johnson, and John Vlissides (Addison-Wesley, 1995).

  The first part contains which is an introduction to design patterns. We added an introductory section for readers with minimal object-oriented program- ming experience. More advanced users may want to skip the review of OOP, but go over the materials on design patterns.

   Parts II, III and, IV are the three major parts of the book. They examine fundamental design patterns, and organize the patterns into creational, structural and behavioral categories. Representative design patterns are included in each part, but we didn’t include every single design pattern from the book by Gamma and his associates.

  

   Part V contains two chapters on using multiple design patterns in application devel- opment. The Model-View-Controller and Symmetric Proxy designs incorporate more than a single design pattern. They’re organized like the other chapters on design pat- terns as far as explaining how the multiple patterns work. However, the multiple designs rely more on object diagrams than class diagrams.

   Each chapter on design patterns is organized to optimize and clarify understanding the purpose of a design pattern and how to use it. The following sections, although not necessarily in this order, can be found in each of the chapters on design patterns:

  • What is the pattern?
  • Key features of the pattern
  • The formal model of the pattern including a class diagram
  • Key OOP concepts found in the pattern
  • Minimalist abstract example
  • Applied examples We organized the book in this manner to provide a well-rounded picture of each design pattern. By explaining the pattern and its key features, we focus on the pat- tern’s function and structure. The formal model and class diagram gives a wider overview, so you can see the structure and the interconnected classes and interface. We also included certain key OOP concepts for the different patterns. We did this for two reasons. First, the intermediate user will be better able to understand the OOP concept at work, and so understand OOP better. Second, we hoped that advanced users could see the concepts as shorthand to quickly determine how the design pattern is structured.

What You Need to Use This Book

  You will need either Flash CS3 or Flex2 to work with the program examples in this book. All the applications were developed in the Flash IDE, so Flex2 developers will need to make modifications, especially where certain features were developed using Flash drawing tools and components.

  A few examples use Flash Media Server 2 (FMS2). The examples using FMS2 can be created using the Developer’s version of FMS2 and can be freely downloaded at

  

You will need either a Windows or LinuxOS to run

  Flash Media Server 2. If you have a “MacTel” Macintosh, you can use the Window OS to run FMS, but if you have an older Macintosh running on the Motorola CPU, you’ll need to have a LAN or Internet access to a Windows or Linuxplatform running FMS2. Alternatively, you can skip the examples with FMS2.

Say It Again, Sam

  One thing we can guarantee is redundancy. We know that people have different styles of learning. Some are conceptual learners, some experiential, and some meta- phorical or any combinations of those, plus others we haven’t heard about yet. So you will see that we use several different ways to say the same thing with the idea that if you don’t get it one way, you’ll get it another. At the same time, we feel that by discussing the same idea or concept in different ways and in different contexts, the specific sense of that concept is better shaped. In looking over reference materials published in books, articles, and online regarding Design Patterns, we found that some materials were not quite accurate in depicting some features. We worked very hard not to make mistakes, and so by providing numerous contexts, we can help filter out what we specifically mean, and, equally important, what we don’t mean. The ultimate authority is always Design Patterns:

  

Elements of Reusable Object-Oriented Software, and if you have any questions about

exactly what we mean, you can always check it out at the original source.

  Over the years, a number of articles, books, dissertations and other treatises have appeared offering suggestions for improving the original design patterns. Some of these documents are quite useful, and even have the endorsement of members of the Gang of Four (GoF)—Erich Gamma, Richard Helm, Ralph Johnson, and John Vlis- sides. Others are not too useful, especially for learning design patterns, and tend to complicate an already complexsubject. As a result, we have not strayed from the path laid down in the original text by GoF.

User’s Guide

  This book, at its core, is an introduction to a relatively advanced topic for writing reusable OOP code for ActionScript 3.0. Like “jumbo shrimp,” an “elementary intro- duction to an advanced topic” is an oxymoron. Advanced developers may want less of the elementary and less senior developers may demand more preparatory materials. Because we cannot measure any reader’s level, we urge you to go through the Table of Contents and flip through the chapters to find what you want. Find your level and use the book at that level. For some, it will be an exercise of reading from cover to cover, while for others it will be a reference work for looking up how ActionScript 3.0 works with different features of design patterns. After all, it’s your book, and you should use it to best suit your needs.

Flex 2 developers

  We developed all the examples for this book using Flash CS3. So, if you’re looking to use these examples for Flex 2, you’ll need to make the appropriate Flex adjustments. In some cases, examples were developed using user-created movie clip classes in the Flash CS3 IDE and stored in the Library panel. These cannot be employed directly using Flex 2. So, if you’re using Flex 2, plan on some workarounds.

Flash Media Server 2 developers

  We have a few examples that use Flash Media Server 2 (FMS2). The examples don’t require anything more than the Developers Version of FMS2. The Developers Ver- sion can be freely downloaded from the Adobe site at

  

. Alternatively, you can skip the examples, or substitute some other

open socket technology.

Companion Tools You’ll Want

  In an ideal world, those reading this book would have a solid background in object oriented programming and ActionScript 3.0. However, ActionScript 3.0 was released in a non-beta format in Flex2 only about sixmonths before this book, and in Flash at about the same time this book was published. So, you may not be familiar with ActionScript 3.0, and this book is not a tutorial in ActionScript 3.0. At a minimum, you will want to keep the ActionScript 3.0 Reference Guide handy along with any other ActionScript 3.0 documentation that comes with Flash CS3. We strongly urge you to get a copy of Design Patterns: Elements of Reusable Object-

Oriented Software sooner or later. At a minimum, check it out of your library. Another book we found to be invaluable is the wonderfully fun and enlightening book, Head First Design Patterns by Eric and Elisabeth Freeman (O’Reilly, 2004). All the examples are in Java, but even so, you’ll learn a great deal about design patterns and OOP. (Working out how to convert the Java examples to ActionScript 3.0 will teach you a lot about ActionScript 3.0 as well—however, before tackling the Java translations, be sure to go over the design pattern examples in this book.) If you don’t have a good ActionScript 3.0 book yet, get one. We can recommend

  

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, and Keith Peters (O’Reilly,

  2006) and Essential ActionScript 3.0 by Colin Moock (O’Reilly, 2007). For a very brief introduction to ActionScript 3.0, take a look at the Short Cut publication,

  

ActionScript 3.0 Programming: Overview, Getting Started, and Examples of New Con-

cepts by Bill Sanders (O’Reilly, 2007). Also, you’ll want an ActionScript 3.0 book on

  object-oriented programming. We’ve included an introduction to OOP in that will suffice for now, and both the Moock and Lott books have some great OOP materials as well. However, a book dedicated to OOP concepts should be part of your library if you plan to write programs on the level of design patterns.

Conventions Used in This Book

  The following typographical conventions are used in this book: Plain text

  Indicates menu titles, menu options, menu buttons, and keyboard accelerators (such as Alt and Ctrl).

  Bold Indicates text that should be entered by the user.

  Italic

  Indicates new terms, URLs, email addresses, filenames, file extensions, path- names, directories, and Unix utilities.

  Constant width

  Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, or the output from commands.

  Constant width bold Shows commands that should be typed literally by the user.

  Constant width italic Shows text that should be replaced with user-supplied values.

  This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution.

Using Code Examples

  This book will help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for per- mission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

  We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “ActionScript 3.0 Design Patterns, by Bill Sanders and Chandima Cumaranatunge. Copyright 2007 O’Reilly Media, Inc.,

  ISBN 978-0-596-52846-1.” If you feel your use of code examples falls outside fair use or the permission given, feel free to contact us at .

How to Contact Us

  Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc.

  1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax)

  We have a web page for this book, where we list errata, examples, and any addi- tional information. You can access this page at:

  

  To comment or ask technical questions about this book, send email to:

  

  For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at:

  

Safari® Enabled

  When you see a Safari® Enabled icon on the cover of your favorite tech- nology book, it means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top technology books, cut and paste code samples, down- load chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.

Acknowledgments

  Since being introduced to design patterns by aYo Binitie, these programming struc- tures have been a topic of close interest. Like a lot of ActionScript developers, we are grateful to Colin Moock for breaching the topic of ActionScript’s use with design patterns, in Essential ActionScript 2.0. We are also grateful to Eric Freeman and Elis- abeth Freeman for their fabulous Head First Design Patterns—even struggling through the Java code, we found it possible to appreciate how design patterns could be used in ActionScript 3.0. At the root of design patterns, we must acknowledge the venerable Gang of Four who produced Design Patterns: Elements of Reusable Object-

  

Oriented Software, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

  We have spent endless hours poring over this tome. Several people at Adobe were very generous with their time in helping out with the ActionScript 3.0 and some insights into design patterns. They include Chris Nuuja, Erica Norton, Geoffrey Williams, Grant Skinner, Jeffrey Mott, Mike Downey, Nivesh Rajbhandari, Peter DeHaan, Robert Penner, Gary Grossman, Ali Mills, Francis Cheng, David Mendels, Gordon Smith, Roger Gonzalez, Sho Kuwamoto, Francis Chen, Emmy Huang, Werner Sharp, Joan Tan, Phil Costa, Mally Gardiner, Asa Whillock, Chris Hock, Tareq Aljaber, San Khong, and Peter von dem Hagen.

  In the Flash community, several Flash developers added further insight to both design patterns and ActionScript 3.0. They include Peter Hall, Aral Balkan, Robert Penner, Beau Ambur, Stefan Richter, Joey Lott, Guy Watson, Keith Peters, Will Law, and Brian Lesser. Jonathan Kaye, who brought state machines to ActionScript, was a huge help by going over a state design pattern that served as a model for what was developed for the book.

   helping to make the arrangements with O’Reilly Publishers. As always, Margot smoothed a complex process.

  We are grateful to Professor John Gray, chair of the Multimedia Web Design and Development program at the University of Hartford. His encouragement and sup- port in all matters pertaining to Internet and Web development, research and learn- ing provide us with a rich atmosphere and wonderful resources to keep on track with the ever expanding universe of the technology we use.

Technical Reviewers

  The technical reviewers had their job cut out for them. Some of the reviewers were experts on design patterns with C# and Java backgrounds, but were unfamiliar with ActionScript. Fortunately, ActionScript 3.0 is looking and acting like other OOP lan- guages, and so they were able to give us a great deal of help. Chief among this group was Adrienne Decker who is a Lecturer in the Department of Computer Science and Engineering at SUNY Buffalo. After sharing a session with Adrienne at the 2006 Object-Oriented Programming, Systems, Languages and Applications (OOPSLA) Conference in Portland, Oregon, it became clear that Adrienne not only was wise in the ways of design patterns, she was also very interested in how to best communi- cate the inner workings of design patterns. She was an immense help. Two other aca- demics recruited to this project were Dr. James Heilotis and Dr. Axel Schreiner, both of the Rochester Institute of Technology, Department of Computer Science. Profes- sor Schreiner had presented a design pattern named the Symmetric Proxy Pattern at the 2006 OOPSLA conference. Based on a paper, A Pattern for Distributing Turn-

  

Based Games, by Heilotis and Schreiner, this new pattern seemed to be an excellent

  tool for gaming over the Internet using Flash and Flash Media Server 2. We believed that given the newness and creativity of the Symmetric Proxy Pattern, we would be well-advised to ask them for a technical review of our implementation and explana- tion of their pattern. They were very helpful in seeing to it that we were able to com- municate their ideas, and we are most grateful to them both. We were most fortunate to get the services of Todd Anderson. Todd is a bright light in the ActionScript 3.0 and design pattern mix. He helped us immensely and we are most grateful to Todd’s sharp eye and spot-on comments. Darren Richardson was our technical reviewer from the outset. He also brought an international perspective in case we got a bit too ethnocentric. We also had the unique opportunity of working with The City’s Flash Coders New York (FCNY) group led by Jean-Charles Carelli. With considerable talent to spare, members of this group worked on (and over) our manuscript as technical reviewers. Their comments were quite helpful, and reflected an excellent cross-section of savvy ActionScript developers. Chief among those who aided in this process were Tyler Lar- son, Jim Kremens, Dominic Tancredi, Shari Halter, James O’Reilly, Andrew Hunt, Brian Weisenthal, Oscar Trelles, Seth Hillinger, Lisa Larson, and Edward Skrypa.

Editors

  Our development editor, Robyn Thomas, had to make sense out of a highly techni- cal corpus of work in addition to guiding us through The King’s English to insure what we said was what we meant. She also kept an array of technical editors sup- plied with chapters, updated where all the pieces were (and where they should be), and generally made the writing experience one of the nicest possible. Steve Weiss is an incredibly supportive publisher—getting everything organized and on track. Steve is also open to new perspectives and all things creative; most likely because he is so creative himself.

Authors

  Bill Sanders, PhD, and Chandima Cumaranatunge, PhD, are both professors in the

  2 Multimedia Web Design and Development (MWD ) program at the University of

  Hartford. Bill teaches courses in Flash, ActionScript, Flash Media Server 2, PHP, C#, SQL, CSS and XHTML among other Internet languages. He has published 44 com- puter and computer-related books, written software ranging from Basic to Flash Media Server ActionScript, and served as a consultant for different computer software companies. Chandima teaches an introduction to the MWDD major, covering Flash and some ActionScript, a gaming course using Flash and ActionScript, as well as educational technology courses in the Education, Nursing, and Health Professions College. Recently he received a grant to teach an experimental course in robotics.

Bill Sanders

  Bill would like to thank his co-author Chandima for a great writing experience and someone to really talk with about design patterns. Bill would also like to thank his wife Delia for her forbearance while she completed her doctorate and our two offices sang the song of two fully employed word processors. Our obsessive-compulsive Greater Swiss Mountain Dog, WillDe, added a measure of reality to both of our efforts. He always knew what was really important—going for a walk.

Chandima Cumaranatunge

  Chandima considers himself very lucky, not only to have Bill as a writing partner, but as a professional mentor and friend. He is also eternally grateful to his wife Resh- maal for being totally supportive and putting up with his long writing stints away from the family. Finally, Chandima’s daughter Sayuri, the two-year-old “little lily” in “the ocean” (based on the meaning of her name in Japanese and Sinhalese) kept him sane by reminding him every day about the important things in life.

  I. PART I Constant Change You must be the change you wish to see in the world.

  —Mohandas Gandhi They must often change, who would be constant in happiness or wisdom.

  —Confucius Without change, something sleeps inside us, and seldom awakens. The sleeper must awaken.

  —Frank Herbert Life belongs to the living, and he who lives must be prepared for changes.

  —Johann Wolfgang von Goethe

  If we had to summarize design patterns in a single sentence, we’d say that they’re

  

tools for coping with constant change in software design and development. When you

  look at the different design patterns in this book, they’re optimized to allow the pro- grammer to make changes and reuse most of the software developed. The key con- cepts are change and flexibility. That same theme will be repeated throughout the book. This Part I provides a general guide for understanding and using this book.

  To work with design patterns, you need to know basic object-oriented programming (OOP) principles. If you’re not familiar with these concepts, spend some quality time with gets into some of the design pattern principles, and understanding these concepts will help you better understand the chapters covering the individual design patterns.

  If you use and understand the basic OOP concepts such as abstraction, encapsula- tion, inheritance and polymorphism, you won’t necessarily be a good OOP designer. As a professional designer and developer, you need to design software that’s easy to maintain and flexible enough to accept change. In other words, you need to develop software that reflects the real world. Any tool you use on the Web today must have the capacity to easily change, be updated, and be reused. Otherwise, the software lacks the capacity to adapt to real world usage.

  Design patterns provide object-oriented designs that can cope with change using dif- ferent OOP tools. If you think about using OOP designs with an eye to how those designs can deal with change, how they can be reused, and how to build in flexibil- ity; then you’re beginning to think like a design pattern programmer.

  

  1 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 speak- ing 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 complexprograms, 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 pos- sible 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 Flexas 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 statements jumping all over a program, subroutines modularly defined pro-

  GOTO gram flow with appropriate GOSUB/RETURN procedures to keep everything tidy.

  RETURN

  The statements back then were different from what they are today. A RETURN meant to return to the position in a sequence of code

  GOSUB return

  where the had originated. In ActionScript, a 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 contami- nate another.

  The great majority of programming languages today are considered procedural in that they have the concepts and syntaxthat 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, lan- guages 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.

  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 meth- ods as procedures to be admitted to the exclusive club of OOP lan- guages. 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 fol- lowing 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 statements associated with or

  on MovieClip

Button objects, you’re probably aware that the latest version of Flash doesn’t allow

  script embedded in either.

  Built-in State Machines: while most programmers welcomed the demise of movie clip and button embedded scripts, one astute pro- grammer observed that Flash used to have built-in state machines. Jonathan Kaye, PhD, co-author of Flash MX for Interactive Simula- tion: How to Construct and Use Device Simulations (Delmar Learning, 2002), noted that the button and movie clip scripts often served to cre- ate state machines. Each button or movie clip could serve as an encap- sulated, context-sensitive trigger for changing state. (See how design

  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 prob- lem 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 Action- Script 2.0, you were able to place a script in a class and call it from a script embed- ded 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. shows how to use the Document class window in the Properties panel to enter the name of the class you want to launch: 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

  Figure 1-1. Document class window

MovieClip class. A Sprite object has no Timeline, but a MovieClip class does. So

  using objects save a bit of extra weight that the Timeline has.

  Sprite

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, 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 use- ful 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 Sym- bol Edit Mode.

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

  Center point Figure 1-2. Rocket drawing

  4. Select Insert ➝ New Symbol from the menu bar to open the Convert to Symbol Dialog box. Enter in the Name window, select Movie clip as Type,

  FireRocket

  and click the Export for ActionScript checkbox. Once you’ve clicked the check- box, 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.

  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

  Current position Ending position Center point

  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 in the same folder as

  TestRocket.as

  the Rocket.fla file. Enter the script in in the TestRocket.as file, and save the file once again:

  Example 1-1. TestRocket.as