BUY THIS BOOK
Add to Cart

Print Book $44.99


Add to Cart

Print+PDF $58.49

Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £27.99

What is this?

Looking to Reprint or License this content?


ActionScript 3.0 Design Patterns
ActionScript 3.0 Design Patterns Object Oriented Programming Techniques By William B. Sanders, Chandima Cumaranatunge
July 2007
Pages: 532

Cover | Table of Contents


Table of Contents

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 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?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Factory Method Pattern
As experimentation becomes more complex, the need for the cooperation in it of technical elements from outside becomes greater and the modern laboratory tends increasingly to resemble the factory and to employ in its service increasing numbers of purely routine workers.
—John Desmond Bernal
The medieval university looked backwards; it professed to be a storehouse of old knowledge. The modern university looks forward, and is a factory of new knowledge.
—Thomas Huxley
One cannot walk through an assembly factory and not feel that one is in Hell.
—W. H. Auden
One of the most common statements in object-oriented programming (OOP) uses the new keyword to instantiate objects from concrete classes. ActionScript applications that have multiple classes can have an abundance of code that looks like the following:
public class Client
{
    public function doSomething()
    {
        var object:Object = new Product();
        object.manipulate();
    }
}
The Client class creates a new instance of the Product class and assigns it to the variable object. There's nothing wrong with this code, but it does create a coupling or dependency between the Client and Product classes. Simply put, the Client class depends on the Product class to function properly. Any changes to the Product class in terms of class name changes or change in the number of parameters passed to it will require changes in the Client class as well. This situation is exacerbated if multiple clients use the Product class, and requires changing code in multiple locations.
The solution to this common problem is to loosen the tight coupling between the client and the concrete classes it uses. This is where the factory method pattern offers a robust solution. It introduces an intermediary between the client and the concrete class. The intermediary is called a creator class. It allows the client to access objects without specifying the exact class of object that will be created. This is accomplished by delegating object creation to a separate method in the creator called a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Singleton Pattern
The aspects of things that are most important to us are hidden because of their simplicity and familiarity.
—Ludwig Wittgenstein
Above all be of single aim; have a legitimate and useful purpose, and devote yourself unreservedly to it.
—James Allen
The Singleton pattern is used all the time, even if you don't realize you're using it. For example, if you have some kind of class that keeps the total number of points in a game, you want only a single instance of that total. It doesn't make any sense to have two totals where the game records only a single total score, like you find in a single-player pinball game. Likewise, if you create a music application, you want the application to play only one tune at a time, and so you want only a single instance of the class that actually plays the music. In fact, most applications have at least some feature where you want to make sure that there's only a single instance, and that's where you'll want to use the Singleton design pattern.
In a nutshell, the Singleton has two key features:
  1. One and only one instance of the class can be instantiated at any one time.
  2. The class must have a single, global access point.
You may be thinking, "How hard can that be? As the developer, I can just instantiate a single instance and use a global variable. Bob's your uncle, and it's all done. Next pattern."
First of all, as you saw in Chapter 1, OOP and design patterns were devised for teams of developers, and not just one person working independently. So if you're involved in teamwork, the Singleton can be used to make sure another developer on the team doesn't create an instance of the class when you've already done so. The Singleton design pattern tells other developers not to create more than a single instance of the base class associated with the pattern.
Second, using global variables in no way restricts their usage to a single instance. They can be instantiated anywhere from a top-level package to within a function inside a class. Global access must go hand-in-hand with single instantiation.
This is not to say creating a Singleton class is difficult. You can create the class using a single file, and there's not a lot of code in the basic class. You can add all the methods and properties you want, and so a Singleton isn't restrictive in that sense. The main issue to wrap your head around is that of making sure only a single instance is invoked at any one time.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Decorator Pattern
I try to decorate my imagination as much as I can.
—Franz Schubert
Pictures deface walls more often than they decorate them.
William Wordsworth (Poet and a guy who really understood bandwidth)
The Decorator pattern wasn't developed with a web designer or developer in mind, but it could well have been. A few years back, we developed a web site and were cognizant of the fact that periodically we'd have to update it. The design was set up so that substitution of one element for an updated one was fairly simple, and it required no major change in the code or structure. Because we didn't have to update it too often, this wasn't much of a problem. However, had we needed to update elements or features on a fairly regular basis, our design would have left a good deal to be desired.
Imagining situations where you need to update or change certain parts of a web site on a regular basis isn't difficult. If your client is a retailer with regular advertising such as weekly specials and new products introduced periodically, you want to have flexibility in your web design and structure. You may want to use features of your basic structure that assure change is easily accommodated, but you don't have to alter the basic structure itself in any way.
The Decorator pattern addresses the issue of maintaining the structure while having the ability to make changes by decorating the different components that make up the application. The decorations are composed of descriptions and/or methods used to wrap different objects in the application. As you will see, this design pattern allows you to mix and match all the different components and decorations to optimize flexibility and expandability, while core structure classes remain unaltered.
We can understand the Decorator pattern in terms of two key features. Often, developers want to add unique responsibilities for an object without adding those same responsibilities to the whole class. Among other design patterns, the Decorator pattern's characterized by adding unique responsibilities. The identifying characteristic of the Decorator pattern is to add responsibilities in a uniquely Decorator fashion. Wrapping a component in an object that adds a responsibility follows a couple of guidelines:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Adapter Pattern
Adapt or perish, now as ever, is nature's inexorable imperative.
—H. G. Wells
The presentations and conceptions of the average man of the world are formed and dominated, not by the full and pure desire for knowledge as an end in itself, but by the struggle to adapt himself favorably to the conditions of life.
—Ernst Mach
The basic motivation for the adapter pattern is to enable wider use of existing classes. For example, let's assume that there's a class that does a particular job, and does it well. We want to use this class in an application, but it just doesn't fit all the current requirements. We may want to expand its features, or combine it with some other classes to provide additional functionality. The bottom line is that we must adapt this existing class to fit new requirements. This is what the adapter pattern does; it allows a client to use an existing class by converting its interface into one that fits a new context. The key point to remember is that the existing class isn't modified, but an adapter class that has the right interface uses it or extends it to provide the necessary functionality.
A good example of an adapter is the toilet seat adapter used by toddlers that fits on top of a traditional toilet seat. Let's take a look at the context. We have a legacy object that is the toilet seat, whose basic design hasn't changed in years. It functions well for its original adult users (probably why the design hasn't changed). Let's look at the new context in . We now need to adapt it for use by a toddler. The problem is obvious - incompatible interfaces! The legacy toilet seat was designed to fit an adult's bottom, and we now need to convert that interface to fit a toddler's smaller bottom. We need an adapter that presents the correct interface to fit the current context. The toilet seat adapter was built to do precisely that. We get to use an existing object whose interface has been converted to one that the client expects.
Figure : Toilet seat adapter
How is this analogous to an adapter pattern? We have an existing object (toilet seat); a new interface it needs to conform to (a toddler's bottom); an adapter that converts the interface (toilet seat adapter); and a new client (toddler).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Composite Pattern
What we need to do is learn to work in the system, by which I mean that everybody, every team, every platform, every division, every component is there not for individual competitive profit or recognition, but for contribution to the system as a whole on a win-win basis.
—W. Edwards Deming
In a logically perfect language, there will be one word and no more for every simple object, and everything that is not simple will be expressed by a combination of words, by a combination derived, of course, from the words for the simple things that enter in, one word for each simple component.
—Bertrand Russell
A complex system that works is invariably found to have evolved from a simple system that works.
—John Gaule
The composite pattern provides a robust solution to building complex systems that are made up of several smaller components. The components that make up the system may be individual objects or containers that represent collections of objects. Think of a car as a complex system that is made up of several smaller components. The car contains an engine, body, chassis, seats, tires, etc. For the sake of simplicity, let's consider a tire as an indivisible or primitive object. A car would be composed of four tires (in reality a tire contains several smaller components such as hubcap, rim, tube, etc.). Similarly, a car contains one steering wheel. However, the engine contains several smaller components such as cylinders, compressor, radiator, etc. The engine is a component of the car, but the engine itself is a collection of components. We refer to a component that is a collection of other components as a composite object. The beauty of the composite pattern is that it allows clients to treat primitive objects and composite objects the same way. For example, when adding, or removing a component, the client doesn't have to bother with figuring out if the object is a primitive or composite object. The client can just as easily remove the engine or a tire through a common interface.
A useful way to understand the composite pattern is to think of complex composite objects as hierarchical trees. We're talking about upside-down trees as in , where the system begins with a root node and cascades down, subdividing into several branches.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Command Pattern
To command is to serve, nothing more and nothing less.
—Andre Malraux
When you do the common things in life in an uncommon way, you will command the attention of the world.
—George Washington Carver
Create like a god, command like a king, work like a slave.
—Constantin Brancusi
The command pattern allows a client to issue requests to an object without making any assumptions about the request, or the receiving object. Think of the request as a command sent to an object to engage in a known behavior. The straightforward way to do this would be to create an instance of the object, and call the method that implements the required command (or behavior). For example, let's assume that we're building a house that allows computer control of many of its components such as lights, doors, heating, etc. Let's look at the code that would turn on a light bulb. The Light class implements a method called on() that turns on a light. A client would execute the following code to turn the light on.
var light = new Light();
light.on();
Let's look at another command to open a door. In this case, the receiver of the command is an instance of the Door class, which implements a method called open() that opens the front door.
var frontdoor = new Door();
frontdoor.open();
Notice the tight coupling between the client and the receivers. By coupling, we mean the degree to which one section of code relies on another section. The client is tightly bound not only to the receiver classes (Light and Door), but to particular methods (on() and open()) in those classes as well. This is not a good situation if we want to have a flexible system that allows future expansion.
What would happen if we replace our ordinary front door with a new sliding door? What if the new class that controls the door is called SlidingDoor, and the method in the class that opens the door is called slideOpen()? We have to modify the code in the client to refer to the new receiver class. Avoid getting into situations that require modifying existing code. In addition, this new situation can require modifications in multiple places. For example, if the front door was controlled from two locations, a wall mounted control panel with buttons assigned to each controlled device and a handheld remote control (like a TV remote), changing the receiver class for the front door would require code changes in both control devices. Also, you couldn't reassign the buttons on the control to a different layout, as the control code is hardcoded to each button.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 8: Observer Pattern
It is the theory that decides what can be observed.
—Albert Einstein
Every man who observes vigilantly and resolves steadfastly grows unconsciously into genius.
—Edward G. Bulwer-Lytton (Author of the immortal line, "It was a dark and stormy night," written while trying to explain how his Internet connection got knocked out and he missed a deadline.)
The world is full of obvious things which nobody by any chance ever observes.
—Sherlock Holmes (Original reference to syntax errors.)
You can observe a lot just by watching.
—Yogi Berra
Conceptually, the Observer design pattern is easy to understand. A central point sends information to subscribing instances. This works just like a newspaper or cable television subscription service. When a person subscribes, the service begins, and continues until he unsubscribes.
In applications where a single source of information needs to be broadcast to several different receptors, using a single source in the design makes more sense than having several different sources getting the same information by repeated calls to the data source. For example, in using a web service that sends out stock quotes, setting up your application to receive the information in a single source, and then sending out that information from that source in your application, is more efficient than having each instance calling the information separately from the web service. If your application takes the incoming stock information and displays the information in tabular and different chart forms, having multiple subscriptions to each of the different formatting classes would require separate and repeated calls to the web service. However, by using a single call to the web service and then broadcasting to the multiple instances, you need far fewer service calls.
In addition to being more efficient, a central data source guarantees that every instance gets the same information. Imagine a change in data from one web service call to the next where a major change occurs. The first instance calls the service and formats the data into a table, and the second instance calls the service to format the data in a bar chat. The data in the chart does not reflect the data in the table, even though it's supposed to. Using an Observer pattern, a single call to the web service
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 9: Template Method Pattern
If you write a post and put it on a blog, that's a historical document. If you change your template, then that entry looks completely different. It's the same words, but not the same meaning. This all depends on what historical questions that people will be asking and we can't know what they will want.
—Josh Greenberg
David Sanborn
Well, I did all the pre-production and I did full demos of all the songs and then I took it into the studio and played it for all the guys and then we kind of took that as the template and did the album live very quickly.
You're going to like this pattern. Essentially the template method is an algorithm made up of a sequence of operations that accomplishes some goal. Imagine a general set of steps for getting something done such as going to work. If you take a car, boat, or airplane to work, you're going to be doing certain things that are similar and others that are different. You'll be transporting yourself in a vehicle, guiding it to a particular location, and you always grab a cup of coffee to take with you. So if you make a general template that covers going by car, boat, or airplane, your outline (algorithm) would look something like the following:
  1. Prepare transportation.
  2. Navigate vehicle.
  3. Drink your cup of coffee.
Preparing a car for transportation usually involves little more than making sure it's got enough gas and the tires aren't flat. With a boat, you might want to check to make sure you have the necessary charts on board and that all the life preservers are in good shape. An airplane requires a walk around with a pre-flight checklist of items to inspect. So, you're going to need special instructions for the first item in the outline depending on the vehicle.
This chapter contains two different types of references to "template method." A reference to the Template Method design pattern will have the first letter of each word capitalized. The template method is also a reference to a method (function), and that reference will use lowercase for both words.
For the second step, navigation in a car requires getting on the road, making all the correct turns, and using the right streets. This can be tricky at times, and the driver may want to check on traffic reports to avoid congestion or road repairs. Depending on the circumstances, a boat trip can be anything from a quick trip across a lake to a complex navigation through shoals, shallows, and currents. Finally, navigating an airplane can be a simple straight flight on a clear day to an IFR (Instrument Flight Rules) flight requiring knowledge of several different navigation instruments in cloudy weather. Like the first step, this too will require specialized instructions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 10: State Design Pattern
A State without the means of some change is without the means of its conservation.
—Edmund Burke
All modern revolutions have ended in a reinforcement of the power of the State.
—Albert Camus
The State design pattern focuses on the different states in an application, transitions between states, and the different behaviors within a state. Looking at a simple light switch application, we can see two states, On and Off. In the Off state, the light is not illuminated, and in the On state, the light illuminates. Further, the light switch transitions from the Off state to the On state using a method that changes the application's state—flipping the switch. Likewise, it transitions from On to Off with a different transition and method. An interface holds the transitions, and each state implements the transitions as methods unique to the state. Each method is implemented differently depending on the context of its use. So, a method, illuminateLight(), for example, would do one thing in the Off state and something entirely different in the On state, even though illuminateLight() method is part of both states.
The following key features characterize the State design pattern:
  • States exist internally as part of an object.
  • Objects change in certain ways when states change. Objects may appear to change classes, but they're changing behavior that is part of the class.
  • Each state's behavior depends on the current state of other states in the object.
One application where the state pattern's popular is device simulation. Devices that change an object's state are subject to change as the states change. The volume knob on a radio changes the sound's volume state. More complex simulated devices include a music sound mixer board where simulated sliders change different states to affect the overall object (sound mixer) and the resulting sound. A Flash video player has several states to manage: play, record, append, pause and stop. Each state in the video player behaves according to the state of the other states as well as its own state.
To understand and appreciate the value of the State design pattern, we need to understand something about
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 11: Strategy Pattern
Enact strategy broadly, correctly and openly. Then you will come to think of things in a wide sense and, taking the void as the Way, you will see the Way as void.
—Miyamoto Musashi (16th-17th Century Japanese developer of Sword Method Design Pattern [Kenjutsu] and guy who reminds us that in ActionScript 3.0 the void statement is all lowercase.)
All men can see these tactics whereby I conquer, but what none can see is the strategy out of which victory is evolved.
—Sun Tzu
However beautiful the strategy, you should occasionally look at the results.
—Winston Churchill (Remark made after finishing up a "Hello world" application using the Strategy pattern.)
The Strategy design pattern is sometimes used to illustrate good OOP practices rather than offered as a design pattern that has focused applications. In one article [Agerbo and Cornils, 98], the authors set up a number of guidelines for judging design patterns. One guideline posits that a design pattern should not be an inherent object-oriented way of thinking. Then they proceed to reject the Strategy design pattern because it seems to be nothing but a collection of fundamental OOP principles!
Whether the Strategy pattern is a true design pattern or just a template for how to go about OOP programming, it has lots to offer. Because the class model looks identical to the State design pattern, we need to spend some time distinguishing the Strategy from the State pattern to show not only how each is unique, but to suggest focal applications each may have.
When looking at the key features of the Strategy pattern, you'll benefit from comparing them with the key features of the State pattern in the previous chapter (Chapter 10). The comparison will not only help you understand the difference between the State and Strategy patterns, it'll also help you better understand each pattern in its own right.
The following key features are used in concert to create the Strategy design pattern, but you will find the same elements when looking at good practices for just about any object-oriented programming:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 12: Model-View-Controller Pattern
According to the standard model billions of years ago some little quantum fluctuation, perhaps a slightly lower density of matter, maybe right where we're sitting right now, caused our galaxy to start collapsing around here.
—Seth Lloyd
We view things not only from different sides, but with different eyes; we have no wish to find them alike.
—Blaise Pascal
The primary symptom of a controller is denial, that is I can't see its symptoms in myself.
—Keith Miller
The Model-View-Controller (MVC) is a compound pattern, or multiple patterns working together to create complex applications. The MVC pattern is most commonly used to create interfaces for software applications, and, as the name implies, consists of three elements.
  • Model: Contains the application data and logic to manage the state of the application
  • View: Presents the user interface and the state of the application onscreen
  • Controller: Handles user input to change the state of the application
The power of the MVC pattern can be directly attributed to the separation of the three elements without overlap in each of their responsibilities. Let's look at each element's responsibilities.
The model is responsible for managing the state of the application. The application logic in the model performs two important tasks: it responds to requests for information about the state of the application, and takes action on requests to change the state.
A view is the external face of the application. Users interact with the application through the view. An application can contain multiple views that can be both inputs and outputs. For example, in the case of a portable digital music player such as an iPod, the screen is a view. In addition, the buttons that control song playback are views as well. The screen shows the name of the current song, song duration, album art, and so on, that communicate the current state of the device. Views don't necessarily have to be visual. In the case of a digital music player, the sound that comes through the headphones represents a view as well. For example, clicking on a button may provide some auditory feedback in the form of the click sound. Changing the volume is reflected in the audio output as well. The auditory feedback corresponds to the state of the application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 13: Symmetric Proxy Pattern
Now an allegory is but a translation of abstract notions into a picture-language, which is itself nothing but an abstraction from objects of the senses; the principal being more worthless even than its phantom proxy, both alike unsubstantial, and the former shapeless to boot. On the other hand, a symbol is characterized by a translucence of the special in the individual, or of the general in the special, or of the universal in the general; above all though the translucence of the eternal through and in the temporal. It always partakes of the reality which it renders intelligible; and while it enunciates the whole, abides itself as a living part in that unity of which it is the representative.
—Samuel Taylor Coleridge
There is no country in the world where machinery is so lovely as in America. It was not until I had seen the water-works at Chicago that I realised the wonders of machinery; the rise and fall of the steel rods, the Symmetric motion of the great wheels is the most beautiful rhythmic thing I have ever seen.
—Oscar Wilde
Computers that are commercially available are symmetric or non-handed but it is possible that some existing software and algorithms are left- or right-handed.
—Philip Emeagwali
One of the more interesting problems for programmers is dealing with interaction over the Internet. This is especially true in the case of games where the developer must work out how two or more players can interact in the context of a set of rules that describe the game. This process gets more challenging when the players are making simultaneous (parallel) moves, and both players won't know the outcome of a turn until both have completed their moves.
One such game is Rock, Paper, Scissors (RPS). In this game, two players simultaneously throw hand signals for a rock (fist), paper (a flat hand) or scissors (a horizontal V-sign with the index and middle fingers). Rock defeats scissors, scissors defeat paper, and paper defeats rock. (See http://www.worldrps.com for details). With such clear, simple and universal rules, the game is an ideal way to discover design patterns that accommodate the role of parallel Internet interaction.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to ActionScript 3.0 Design Patterns