ebook img

ActionScript 3.0 design patterns PDF

523 Pages·2007·2.339 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview ActionScript 3.0 design patterns

ActionScript 3.0 Design Patterns William B. Sanders and Chandima Cumaranatunge Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo 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 are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 [email protected]. Editor: Steve Weiss Indexer: John Bickelhaupt Developmental Editor: Robyn G. Thomas Cover Designer: Karen Montgomery Production Editor: Philip Dangler Interior Designer: David Futato Copyeditor: Sohaila Abdulali Illustrators: RobertRomanoandJessamynRead 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. Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas 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] Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Part I. Constant Change 1. Object-Oriented Programming, Design Patterns, and ActionScript 3.0 . . . . . 3 The Pleasure of Doing Something Well 3 OOP Basics 10 Abstraction 11 Encapsulation 15 Inheritance 24 Polymorphism 34 Principles of Design Pattern Development 42 Program to Interfaces over Implementations 45 Favor Composition 49 Maintenance and Extensibility Planning 57 Your Application Plan: It Ain’t You Babe 60 Part II. Creational Patterns 2. Factory Method Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 What Is the Factory Method Pattern? 65 Abstract Classes in ActionScript 3.0 68 Minimalist Example 69 Hiding the Product Classes 73 Example: Print Shop 74 Extended Example: Color Printing 80 Key OOP Concepts Used in the Factory Method Pattern 84 vii Example: Sprite Factory 84 Example: Vertical Shooter Game 90 Summary 100 3. Singleton Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 What Is the Singleton Pattern? 101 Key OOP Concepts Used with the Singleton Pattern 102 Minimalist Abstract Singleton 105 When to Use the Singleton Pattern 112 Summary 125 Part III. Structural Patterns 4. Decorator Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 What Is the Decorator Pattern? 129 Key OOP Concepts Used with the Decorator Pattern 132 Minimalist Abstract Decorator 135 Applying a Simple Decorator Pattern in Flash: PaperDoll 141 Decorating with Deadly Sins and Heavenly Virtues 148 Dynamic Selection of Concrete Components and Decorations: A Hybrid Car Dealership 164 Summary 176 5. Adapter Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 What Is the Adapter Pattern? 177 Object and Class Adapters 179 Key OOP Concepts in the Adapter Pattern 185 Example: Car Steering Adapter 185 Extended Example: Steering the Car Using a Mouse 193 Example: List Display Adapter 194 Extended Example: Displaying the O’Reilly New Books List 199 Summary 203 6. Composite Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 What Is the Composite Pattern? 204 Minimalist Example of a Composite Pattern 207 Key OOP Concepts in the Composite Pattern 217 Example: Music Playlists 217 Example: Animating Composite Objects Using Inverse Kinematics 222 viii | Table of Contents Using Flash’s Built-in Composite Structure: theDisplayList 233 Summary 243 Part IV. Behavioral Patterns 7. Command Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 What Is the Command Pattern? 247 Minimalist Example of a Command Pattern 251 Key OOP Concepts in the Command Pattern 255 Minimalist Example: Macro Commands 255 Example: Number Manipulator 258 Extended Example: Sharing Command Objects 263 Extended Example: Implementing Undo 266 Example: Podcast Radio 270 Extended Example: Dynamic Command Object Assignment 276 Summary 281 8. Observer Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 What Is the Observer Pattern? 282 Key OOP Concepts Used with the Observer Pattern 285 Minimalist Abstract Observer 289 Example: Adding States and Identifying Users 294 Dynamically Changing States 302 Example: Working with Different Data Displays 318 Summary 330 9. Template Method Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 What Is the Template Method Pattern? 331 Key OOP Concepts Used with the Template Method 335 Minimalist Example: Abstract Template Method 338 Employing Flexibility in the Template Method 341 Selecting and Playing Sound and Video 344 Hooking It Up 351 Summary 356 10. State Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Design Pattern to Create a State Machine 357 Key OOP Concepts Used with the State Pattern 360 Minimalist Abstract State Pattern 361 Table of Contents | ix Video Player Concrete State Application 367 Expanding the State Design: Adding States 374 Adding More States and Streaming Capabilities 382 Summary 397 11. Strategy Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 What Is the Strategy Pattern? 398 Key OOP Concepts Used with the Strategy Pattern 400 Minimalist Abstract State Pattern 402 Adding More Concrete Strategies and Concrete Contexts 406 Working with String Strategies 414 Summary 423 Part V. Multiple Patterns 12. Model-View-Controller Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 What Is the Model-View-Controller (MVC) Pattern? 427 Communication Between the MVC Elements 428 Embedded Patterns in the MVC 430 Minimalist Example of an MVC Pattern 431 Key OOP Concepts in the MVC Pattern 443 Example: Weather Maps 443 Extended Example: Infrared Weather Maps 451 Example: Cars 457 Custom Views 463 Adding a Chase Car 466 Summary 468 13. Symmetric Proxy Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 Simultaneous Game Moves and Outcomes 469 The Symmetric Proxy Pattern 473 Key OOP Concepts Used with the Symmetric Proxy 475 The Player Interface 477 The Referee 478 Information Shared Over the Internet 483 Player-Proxy Classes 486 Classes and Document Files Support 494 Summary 498 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 x | Table of Contents Preface 1 AsActionScripthasevolvedfromafewstatementsinFlashtoafull-fledgedInternet 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 Flex program- ming because it implements the ECMAScript standard for Internet languages. Many features found in languages such as C++ and JavaTM are now available in Action- Script 3.0. AlongwithmoresophisticatedfeaturesinActionScript3.0comemoresophisticated ways of programming and thinking about programming. Most readers of this book willbefamiliarwithOOPtosomedegree,andlikethestepfromsequentialorproce- duralprogrammingtoOOP,thesteptodesignpatternprogrammingisastepupfor OOP programmers. We felt that because ActionScript 3.0 had arrived at a point where more complex and challenging programming structures can be developed, FlashandFlexprogrammersneededtounderstandprogrammingtechniquestocope with these structures. Byunderstandingdesignpatternprogramming,youwillbeabletowritebetterOOP code,andreusethatcodeinotherprograms.Thebetterpayingpositionsinthepro- 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.Atthesametimethatyougainproficiencyinprogrammingmorecomplexappli- cations, design patterns actually make programming easier. In large and complex applications, programmers have the most difficulty with poor planning and awk- warddesignstructures.Designpatternsnotonlyprovidesolutionsforcommonchal- lenges,butalsofocusonmaintenanceandchange.Thevocabularyofdesignpatterns is equally important because with it, you can become part of the developer commu- nity that communicates clearly in the language of design patterns. xi 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 backgroundsarefarmorevaried,andtheprogrammingbaselessdefinite.We’resure 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’recertainthatsomereadersonthelowerendoftheintermediate levelarelearningobject-orientedprogrammingatthesametimethatthey’retryingto 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 intermediatelevelActionScriptdevelopers.We’veprovidedeverythingtheintermedi- 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 Thebook’sorganizationreflectsthetopicorganizationfoundinDesignPatternsEle- ments of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995). The first part contains Chapter1, which is an introduction to design patterns. We added an introductory section for readers with minimal object-oriented program- mingexperience.MoreadvancedusersmaywanttoskipthereviewofOOP,butgo over the materials on design patterns. Part I,Constant Change Chapter1,Object-Oriented Programming, Design Patterns, and ActionScript 3.0 PartsII,IIIand,IVarethethreemajorpartsofthebook.Theyexaminefundamental 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 II,Creational Patterns Chapter2,Factory Method Pattern Chapter3,Singleton Pattern xii | Preface Part III,Structural Patterns Chapter4,Decorator Pattern Chapter5,Adapter Pattern Chapter6,Composite Pattern Part IV,Behavioral Patterns Chapter7,Command Pattern Chapter8,Observer Pattern Chapter9,Template Method Pattern Chapter10,State Pattern Chapter11,Strategy Pattern Part V contains two chapters on using multiple design patterns in application devel- opment.TheModel-View-ControllerandSymmetricProxydesignsincorporatemore thanasingledesignpattern.They’reorganizedliketheotherchaptersondesignpat- terns as far as explaining how the multiple patterns work. However, the multiple designs rely more on object diagrams than class diagrams. Part V,Multiple Patterns Chapter12,Model-View-Controller Pattern Chapter13,Symmetric Proxy Pattern 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. Preface | xiii What You Need to Use This Book YouwillneedeitherFlashCS3orFlex2toworkwiththeprogramexamplesinthis book.AlltheapplicationsweredevelopedintheFlashIDE,soFlex2developerswill 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 createdusingtheDeveloper’sversionofFMS2andcanbefreelydownloadedathttp:// www.adobe.com/downloads/. You will need either a Windows or Linux OS to run FlashMediaServer2.Ifyouhavea“MacTel”Macintosh,youcanusetheWindowOS torunFMS,butifyouhaveanolderMacintoshrunningontheMotorolaCPU,you’ll need to have a LAN or Internet access to a Windows or Linux platform 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 thesedocumentsarequiteuseful,andevenhavetheendorsementofmembersofthe 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 complex subject. As a result, we have not strayed from the path laid down in the original text by GoF. xiv | Preface

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.