ActionScript 3.0 TouchEvent: Guaranteed Mobile Speedup
I suppose old habits die hard, especially when those habits still work. (Some programmers are fond of saying, If it ain’t broke, don’t fix it! and the similarly dull-witted proverb, Don’t re-invent the wheel!) Well, with mobile devices, you’d better think about breaking old habits, and I put myself at the top of the dullard list for taking so long to make some adoptions. One of the first changes to make when creating mobile apps is to use the TouchEvent instead of the MouseEvent. In working on a game, I merrily kept using MouseEvent until I noticed that my apps kept getting stuck in the mud when I put them on a mobile device. So, I decided to give TouchEvent a try. Naturally, I couldn’t test in Flash Pro CS5.5; so I had to wait until I launched it in my iPhone. When I did, the difference was night and day. The sluggishness disappeared.
The good news is that MouseEvent and TouchEvent classes work pretty much the same as far as programming them into an app. I have no idea what’s going on with either under the hood, and I shouldn’t have to concern myself with those issues other than to know that one works better with mobile devices than the other. To get started, we’ll take a look at the sequence for setting up for TouchEvents, and while almost identical to MouseEvent, there are programming differences. First, though, click the Play button to see the little testing app on your computer. You can also download the Flash 5.5 Fla file and Client class by clicking on the Download button.
![]()
![]()
As you can see it’s a simple little app to move a “Samurai” character left and right; up and down. The buttons are in Japanese, and if you read Japanese, you’ll realize that the characters look like a first-grader’s attempts to learn how to write in Japanese. (Feel free to make some better simple buttons using Japanese characters and send them along with any comments you may have.)
Possible Controversy: After I had finished this post, I ran across the following:
http://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b0-6ffb37601221e58cc29-8000.html
In it is a note of caution:
Note: Listening for touch and gesture events can consume a significant amount of processing resources (equivalent to rendering several frames per second), depending on the computing device and operating system. It is often better to use mouse events when you do not actually need the extra functionality provided by touch or gestures. When you do use touch or gesture events, consider reducing the amount of graphical changes that can occur, especially when such events can be dispatched rapidly, as during a pan, rotate, or zoom operation. For example, you could stop animation within a component while the user resizes it using a zoom gesture.
That certainly makes sense, but I found that even using TOUCH_TAP, it was a quicker and far more responsive than listening for a CLICK event. There’s only one way to resolve this issue; try it yourself with a mobile app on a mobile device–any one you want. Use the Comment section to report what you’ve found. The sample app is as good as any for a trial, but feel free to create one of your own choosing.
As Chico Marx remarked in Duck Soup, Well, who you gonna believe, me or your own eyes? Believe your eyes and give it a whirl!
Just the Right Touch
Setting up the TouchEvent includes three imports:
- import flash.events.TouchEvent;
- import flash.ui.Multitouch;
- import flash.ui.MultitouchInputMode;
That contrasts with the single MouseEvent import required when using the mouse event. However, prior to using the TouchEvent class you have to set up your mobile context with the following line:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
That statement focuses the input mode to touch instead of a mouse event. I was unable to get the TouchEvent to work without the statement; so, don’t forget to include it in your program.
Finally, you need an event listener, and it has the same format as a mouse event except you use TouchEvent. Also, instead of using CLICK, use TOUCH_TAP, as the following illustrates:
upBtn.addEventListener(TouchEvent.TOUCH_TAP,moveNow);
With that knowledge, you’re all set to set up an app using TouchEvent.
Many Ears; One Handler
One of the big memory hogs in programming, especially noticeable in mobile devices, is event listening. Each event listener sets up a series of operations that have to keep listening for an event. Having a single event won’t help, but it’s a step in the direction of having a single listener (which will help). The following Client sets up an example of using the TouchEvent. All of the buttons are SimpleButton objects and the background is a big Sprite. Likewise, Sam3 is a Sprite that you can move around using tap on your mobile device.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | package { import flash.display.Sprite; import flash.display.SimpleButton; import flash.events.TouchEvent; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; public final class Client extends Sprite { private static var leftBtn:SimpleButton=new Left(); private static var rightBtn:SimpleButton=new Right(); private static var upBtn:SimpleButton=new Up(); private static var downBtn:SimpleButton=new Down(); private static var bkground:Sprite=new Background(); private var sam3:Sprite=new Sam3(); public function Client() { addChildAt(bkground,0); setControls(); setSamurai(); } private final function setControls():void { Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; upBtn.x = 825,upBtn.y = 19; upBtn.addEventListener(TouchEvent.TOUCH_TAP,moveNow); addChild(upBtn); leftBtn.x = 740,leftBtn.y = 106; leftBtn.addEventListener(TouchEvent.TOUCH_TAP,moveNow); addChild(leftBtn); rightBtn.x = 873,rightBtn.y = 105; rightBtn.addEventListener(TouchEvent.TOUCH_TAP,moveNow); addChild(rightBtn); downBtn.x = 825,downBtn.y = 202; downBtn.addEventListener(TouchEvent.TOUCH_TAP,moveNow); addChild(downBtn); } private final function setSamurai():void { sam3.x=(960/2); sam3.y=(640/2)+100; addChild(sam3); } private final function moveNow(e:TouchEvent):void { switch(e.target.name) { case "instance11": sam3.y -=5; break; case "instance1": sam3.x -=5; break; case "instance6": sam3.x +=5; break; case "instance16": sam3.y +=5; break; } } } } |
I set it up to be viewed from a landscape perspective because of a larger project I’m developing. Also, as you can see in the moveNow method, there are no “brakes” on the movement, and so the character can move anywhere, including right off the stage. Currently, I have a nicely working global movement system set up using a State Pattern, and I’d like to integrate both local and global movement into a single movement. Not only would this cut down on the number of listeners, but it would also provide a more interesting game. Figure 1 shows how it looks on an iPhone, and I’d like any feedback if tried on Android or other non-iOS devices.

The 960 x 640 size is compressed to fit in an iPhone environment
You also might want to swap out the TouchEvent for a MouseEvent and try it again in a mobile device. You’ll find that it gets “stuck” after a few clicks. As always, we’re interested in your comments and feedback.
ActionScript 3.0 Single Class Event Handler
The first time I read Scott Petersen’s article on optimizing code for iOS devices, I got it wrong in terms of what he was trying to do in one of the optimizations. In re-reading it, I discovered an interesting structure Scott included, and while not a speed tweak in and of itself, I thought it deserved a short discussion and example.
The idea is to have one object with several methods handle all event requests. A single method handles a single request. As you know, event-requests expect one parameter–the event-object listening for the event. Once initiated, the event.target object can be used to determine an appropriate course of action. To see how this works, I put together a simple class for handling requests. It does nothing more than trace back the label of the UI that makes the initial request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package { import flash.events.MouseEvent; public final class OneNav { public final function navNorth(e:MouseEvent):void { trace(e.target.label); } public final function navSouth(e:MouseEvent):void { trace(e.target.label); } public final function navEast(e:MouseEvent):void { trace(e.target.label); } public final function navWest(e:MouseEvent):void { trace(e.target.label); } } } |
With the OneNav class, the Client can then address all event handlers to the same class (object) and just append the specific method to the object. The general format is:
listeningObj.addEventListener(MouseEvent.CLICK,actionObj.actionMethod);
So now the developer can have everything to be handled in a single class with methods taking care of the details. If the details change, the developer can just go change the methods to reflect the changed details. To test it out, I’ve included the following Client class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package { import flash.display.Sprite; import fl.controls.Button; import flash.events.MouseEvent; public final class Client extends Sprite { private var btnNorth:Button=new Button(); private var btnSouth:Button=new Button(); private var btnEast:Button=new Button(); private var btnWest:Button=new Button(); private var navNow:OneNav=new OneNav(); public function Client() { btnNorth.addEventListener(MouseEvent.CLICK,navNow.navNorth); btnNorth.x=50;btnNorth.y=50; btnNorth.label="North"; addChild(btnNorth); btnSouth.addEventListener(MouseEvent.CLICK,navNow.navSouth); btnSouth.x=50;btnSouth.y=80; btnSouth.label="South"; addChild(btnSouth); btnEast.addEventListener(MouseEvent.CLICK,navNow.navEast); btnEast.x=50;btnEast.y=110; btnEast.label="East"; addChild(btnEast); btnWest.addEventListener(MouseEvent.CLICK,navNow.navWest); btnWest.x=50;btnWest.y=140; btnWest.label="West"; addChild(btnWest); } } } |
In some respects, this technique can add more work for the developer as he tries to figure out how to get the events to spark something on the viewing area even if he’s using a design pattern. This particular implementation reflects work I’ve been doing on the navigation portion of a game I’m developing, but the technique could apply to virtually any project. I would have to have the OneNav method call a State Pattern to get the appropriate image to show up on the stage. The would take a bit of doing. However, for some other kind of application, it might be just the thing you need.
A Final Word
One of the speed tweaks that Scott points out in this same article is using final in marking classes and methods. If you’re not subclassing a given class, you can mark it final as done in the Client class. Marking a class final allows compile-time determination of the exact function being called. When some methods of a class can be overridden, you cannot mark the class final but you can mark the individual method as final, as was done in the OneNav class.
As a matter of fact, I cannot think of a single use case where I would subclass a Client class, and so, it’s probably a safe bet to mark all Client classes as final. When developing with ActionScript 3.0 for mobile devices, every single speed tweak matters.
From ActionScript 3.0 to JavaScript Chain of Responsibility: Part II The Help Desk
I’ve always liked JavaScript, but after going through this last project of creating a design pattern with JS, I find that I like ActionScript 3.0 even more than I did before. The biggest problems that I encountered with JavaScript is that different users slipped in different frameworks (e.g., Prototype.js) and didn’t seem to mention it. My goal was to create a JS design pattern with pure unadulterated JavaScript—not using JQuery, JSon or some other helpful framework. Now, don’t get me wrong—I appreciate a good framework as much as the next guy. However, when I’m trying to create a design pattern for a general language like JavaScript, I’d rather not have to have readers run out and get one framework or another. I wanted this to work with Plain Vanilla JavaScript. So that’s what you’re going to get.
To get started, I took a look at some articles on JavaScript and classes, inheritance and OOP in general. Then I looked at some implementations of JavaScript with a Chain of Responsibility pattern. A lot of them didn’t make a bit of sense, and that’s when I realized that they were slipping in different “helpers,” and so I went back to the most basic JavaScript OOP I knew of–the 1999 book, JavaScript Objects by Nakhimovsky and Myers. Starting there, I pretty much followed that Chain of Responsibility pattern we had in Part I of this two-part series. However, instead of a mobile browser detector, I created a “Help Desk.”
Before continuing, take a look at the “Help Desk” app made with the JS CoR:
![]()
Inheritance is a ‘IS-A’
First I made an abstract Handler class using a single concrete and single abstract method. It seemed to me that classes in JavaScript could be abstract simply by adding a method with no content. I came up with the following class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function Handler()
{
//Handler 'abstract class'
}
Handler.prototype.setSuccessor=function(successor)
{
this.successor=successor;
}
Handler.prototype.handleRequest=function(req)
{
//Abstract method overridden in concrete implementation
} |
I realize that it looks strange compared to more mature OOP languages like ActionScript 3.0 (not to mention Java and C++), but remember, I’m using pure native JavaScript. You create the class by the simple expedient of a function. Then, I create the methods for the class by using a Class.prototype. The class Handler now has the setSuccessor and handleRequest methods, just as we had in the ActionScript 3.0 version. So, while it looks a little goofy for creating classes and their methods and properties, that’s how it’s done.
So far so good, and it’s not rocket science. However, the next part gets a little dicey and may pop a few brain nodes. When you extend a class in JavaScript, you first instantiate the parent class. As we all know, you do not instantiate abstract classes or any other interface. They’re extended or implemented. However, that’s not the case with JavaScript. Take a look at this first child class of Handler:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //AS3DP inherits handler
AS3DP.prototype= new Handler();
function AS3DP()
{
//AS3DP 'class'
}
AS3DP.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="as3dp")
{
document.write("Naturally you want to read <em>ActionScript 3.0 Design Patterns</em> and visit our blog at as3dp.com.");
}
else if(this.successor != null)
{
document.write("Not AS3DP<br/>");
this.successor.handleRequest(this.req);
}
} |
If you recall, basic design pattern principles, a child class “Is-A” parent class. When a JavaScript object (like AS3DP) is instantiated, it is done by declaring itself as a new Handler(). So rather than becoming a child of the parent through extension, JavaScript uses the object prototype to declare itself as an instance of the parent. It’s actually easier to see that a child class indeed “Is-A” parent because the prototype declares itself as such.
As we have seen, the methods and properties have been created outside of the class constructors. Instead of being in the class, they are in the prototype. For now, you can think of the class as the “concept of an object” and it creates and stores the properties for that concept in prototypes. So, knowing that, we can create the rest of the concrete handlers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | //Game inherits Handler
Game.prototype= new Handler();
function Game()
{
//Game 'class'
}
Game.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="game")
{
document.write("As the states change, you want a good state machine like the State Design Pattern.");
}
else if(this.successor != null)
{
document.write("Not State pattern<br/>");
this.successor.handleRequest(this.req);
}
}
//Algorithm inherits Handler
Algorithm.prototype= new Handler();
function Algorithm()
{
//Algorithm 'class'
}
Algorithm.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="algorithm")
{
document.write("The Strategy Design Pattern lets you access different algorithms directly without having to use conditional statements!");
}
else if(this.successor != null)
{
document.write("Not Strategy pattern<br/>");
this.successor.handleRequest(this.req);
}
}
//Factory inherits Handler
Factory.prototype= new Handler();
function Factory()
{
//Factory 'class'
}
Factory.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="factory")
{
document.write("The Factory Method design pattern will unlink the request to build an object from the actual object creation.");
}
else if(this.successor != null)
{
document.write("Not Factory<br/>");
this.successor.handleRequest(this.req);
}
}
//ToInterface inherits Handler
ToInterface.prototype= new Handler();
function ToInterface()
{
//ToInterface 'class'
}
ToInterface.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="tointerface")
{
document.write("The first principle is to <em>Program to the interface and not the implementation.</em> When you declare a new object, type it to the object's parent class; not the object itself.");
}
else if(this.successor != null)
{
document.write("Not Program to Interface<br/>");
this.successor.handleRequest(this.req);
}
}
//Truth inherits Handler
Truth.prototype= new Handler();
function Truth()
{
//Truth 'class'
}
Truth.prototype.handleRequest=function(req)
{
document.write("You know I can't handle the truth! Go visit a muse, a swami, or 3-year old.<br/>");
} |
As you no doubt have noticed, this Chain of Responsibility implementation is not about mobile devices and their languages. Instead, it’s a “Help Desk” that I think is more typical of what you may actually use a CoR pattern for—either in JavaScript or ActionScript 3.0.
All that’s left is to do with the JavaScript is to create instances of the different handlers and set the chain of successors. The “client” that makes the requests is the HTML5 UI.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //'Instantiate Concrete Handlers' var as3dp = new AS3DP(); var game=new Game(); var algorithm=new Algorithm(); var factory=new Factory(); var tointerface=new ToInterface(); var truth=new Truth(); //Set successors as3dp.setSuccessor(game); game.setSuccessor(algorithm); algorithm.setSuccessor(factory); factory.setSuccessor(tointerface); tointerface.setSuccessor(truth); |
You can set up the successors in any way you want except the last one has to be to the Truth class. It has no successor and is meant to be the caboose of the chain. Before going on, place all of the JavaScript into a single file and save it as “HelpDesk.js” and put it in the same folder (directory) as the HTML5 program that follows.
The HTML5 Client
Like most work with JavScript, the UI is in HTML. This is no different. All it does is to call the top of the chain (AS3DP instance) and make a request. All of the requests look like the following:
onclick=”as3dp.handleRequest(‘algorithm’);
The click handler calls the top of the chain, and the Chain of Responsibility just chugs on through until it finds what you want. Here’s the whole HTML5 code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {
font-family:Verdana, Geneva, sans-serif;
color:#1D232;
background-color:#dddcc5;
font-size:12px;
}
h2 {
font-family:"Arial Black", Gadget, sans-serif;
font-size:24px;
text-align:center;
color:#611427;
}
form {
color:#6A6A61;
}
h3 {
background-color:#611427;
color:#958976;
font-size:18px;
}
</style>
<script type="text/javascript" src="HelpDesk.js">
</script>
<meta charset="UTF-8">
<title>Billz Help Desk</title>
</head>
<body>
<header>
<h2>Billz Help Desk</h2>
</header>
<article>
<header>
<h3> Chain of Responsibility: JavaScript</h3>
</header>
<section> This is a simple Chain of Responsibility (CoR) application. Each button represents a different request that the CoR will handle. In this case, the help is in the form of a 'Help Desk' and the CoR finds the appropriate response to the query.<br/>
<br/>
<form>
<input type=button value="Make Request" onclick="as3dp.handleRequest('as3dp');" />
How do I learn about design patterns for ActionScript 3.0 <br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('game');" />
I'm making a game where states keep changing. What would be a good design pattern for dealing with changing states?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('algorithm');" />
My app involves a lot of problem solving with different algorithms? What's a good pattern for dealing with multiple algorithms?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('factory');" />
Whenever I create a new object with my Client object, I build up dependencies. Is there a pattern to avoid such dependencies?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('tointerface');" />
What is a primary guiding design pattern principle?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('truth');" />
I want to know the truth!<br/>
</form>
</section>
<br/>
<section>The CoR pattern works sequentially so that as it moves through the chain, you can see each rejected attempt to find the correct handler. (Normally, you wouldn't see those rejected handlers.) It is a very easy pattern to update and add additional handlers.</section>
</article>
</body>
</html> |
So, now you’re all set to use JavaScript for design patterns. The plain vanilla JS has limitations doing OOP, but you can harness it and bend it to your OOP will. The many different frameworks that work in conjunction with basic JavaScript will make it look more like an OOP language, but you can get by without. There’s a lot to be done with even the most unadorned JavaScript, and I tested the app on an iPhone, and it works fine. However, I’ll bet that several of you can find better ways to handle either the JavaScript or HTML5 (or both) with design patterns, and we’d like to hear from you. Naturally, if you have a favored framework that makes OOP work more efficient, let us know—even better send a design pattern example.
From ActionScript 3.0 to JavaScript Chain of Responsibility: Part I

After Mom, Ask Dad, and then the Dog
To get started on the quest to see whether useful design patterns can be created with JavaScript, I thought it’d be a good idea to go from the known to the unknown. In this case, those familiar with this blog know ActionScript 3.0 design patterns, and the unknown (for some at least) is JavaScript. Well, I suppose just about everyone who reads this blog knows something about JavaScript, but several may not have been involved with either JavaScript OOP or design patterns. By creating an ActionScript 3.0 app using a pattern and then going through the app step-by-step, readers may be better able to understand how we might approach design patterns using JavaScript. I decided to use the Chain of Responsibility (CoR) pattern to go through the types of mobile operating systems that we examined in the previous post. In this way, we can create something both familiar and practical.
Every time I use the Chain of Responsibility pattern, I feel that I’m swatting a fly with a weapon of mass destruction. I see all of these classes, and I’m thinking that I could have done the same thing with a switch statement or something even slicker. Then I need to remind myself why I’d use the CoR in the first place.
The Chain of Responsibility separates the handling of an event from the request to handle it.
In a broader context, this allows the developer to make changes to either the request or the handling of the event without disrupting some other part of the program. It’s quite simple as well. Just imagine several people lined up with different kinds of expertise and/or authority. A request is issued, and once it reaches the person with the right expertise or authority, it is handled. The request is separated from the way it will be handled. That’s up to the expert. Figure 1 shows the class design:

Figure 1: Chain of Responsibility Pattern
Getting Started with CoR
For details about ways to setup and use CoR see our original discussion . The focal points are in the following:
- An interface (an abstract class or interface) establishes a handler operation
- Each request handler has a separate class derived from the handler interface
- Each handler class has a successor which is another handler class
- The last handler in the chain has no successor
- As soon as a handler can handle the request, the chain stops and the handler takes care of the request.
You may be thinking that this is not very efficient since it requires a sequential path. We’ve considered ways to get around a sequence (see our posts on Skip Lists), but for now we’ll stick with the traditional CoR and use a sequential search through the list of handlers.
The Chain of Mobile Operating Systems
This CoR simulates finding one of several types of mobile OS. Given the type of OS, it looks for ways to handle each one optimally. In the JavaScript version of this, we want to have it select a CSS file or another JS file to best use the kind of mobile device involved. The concrete handler classes are the objects used to deal with whatever requirements are necessary. In the example, each handler simply traces out “Set up for xxOS,” where “xx” is the found mobile OS. It also traces out which handlers were rejected so that you can better see how the chain works. Since Android is at the top of the chain, you see no rejections, while Windows CE at the bottom of the chain displays the whole chain.
It might be helpful if you take a look at the whole concept of Linked Lists. The Chain of Responsibility is something like a linked list, but instead of linking lists, it links handlers.
The Client class makes the initial request and sets up a simple requesting UI for testing the application. It makes requests using a string. I just used the lowercase ID of the main mobile OS types as the “request-to-handle.” After making the request, the “chain” takes over. In this example the top of the chain is the Android, but it could be any of the others as well. The developer has complete control over the sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | package { import flash.display.Sprite; import flash.events.MouseEvent; import fl.controls.Button; import fl.controls.TextInput; import fl.controls.Label; import flash.text.TextFieldAutoSize; public class Client extends Sprite { //Handlers + Request private var android:Handler= new Android(); private var iphone:Handler= new IPhone(); private var blackberry:Handler= new Blackberry(); private var series60:Handler=new Series60(); private var windowsce:Handler=new WindowsCE(); private var cannothandle:Handler=new CannotHandle(); //UI private var btn:Button=new Button(); private var iput:TextInput=new TextInput(); private var lbl:Label=new Label(); public function Client() { setupChain(); setupUI(); } private function setupChain():void { //Sequence set up here android.SetSuccessor(iphone); iphone.SetSuccessor(blackberry); blackberry.SetSuccessor(series60); series60.SetSuccessor(windowsce); windowsce.SetSuccessor(cannothandle); } private function setupUI():void { //This simulates getting the mobile OS from the using system lbl.autoSize = TextFieldAutoSize.LEFT; lbl.text="Enter name of mobile device: (Use lower case.)"; lbl.x=50,lbl.y=30; addChild(lbl); btn.x=50, btn.y=75; btn.label="Start the chain"; btn.addEventListener(MouseEvent.CLICK,requestOS); addChild(btn); iput.x=50,iput.y=50; addChild(iput); } private function requestOS(e:MouseEvent) { android.HandleRequest(iput.text); } } } |
For the end of the chain, I added a “CannotHandle” class that extends the Handler interface. This functions something like a default option in a switch statement. If none of the handlers can handle the request, you need to provide the user with some kind of feedback.
Read more…
Can JavaScript Create Design Patterns?

Face the Facts: We've got to deal with Mobile
At this point in time I can easily create a script to determine whether a browser is mobile or non-mobile. I want to get to the point where I can put together a Chain of Responsibility pattern so that I have a flexible design for tweaking a specific kind of mobile device (e.g., calling up appropriate CSS). This requires OOP JavaScript, and so I had to revisit my old JavaScript work. One of the best books on both OOP and JavaScript is Javascript Objects: Object Use and Data Manipulation with JavaScript by Alenander Nakhimovsky and Tom Myers published by Wrox in 1998. It was written by a couple of professors at Colgate University and is pitched at a pretty high level that most readers of this blog will appreciate. (You can still get it from Amazon, and it’s a gem to have no matter what language you favor.) Another good book that deals with JavaScript objects is Douglas Crockford’s JavaScript: The Good Parts (O’Reilly, 2008). Crockford understands JavaScript down to the metal and has great explanations and examples.
So the question is:
Can JavaScript handle OOP and Design Patterns?
To find out, I started writing some prototype classes but found I’d have to spend some more time trying to cobble something together that was both reasonable (it maintains the DP value of flexibility, update and reuse) and real (I didn’t want to make a phony DP with hack classes.) However, it didn’t take long to put together a little code that works to filter out both different mobile devices and non-mobile devices. My plan is to take this code and change it so that I can do the same thing with a Chain of Responsibility design pattern. Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | // JavaScript Document
var sniffer=new Object();
var agentNow=navigator.userAgent.toLowerCase();
sniffer.android=(agentNow.search("android")>=0);
sniffer.series60=(agentNow.search("series60")>=0);
sniffer.iphone=(agentNow.search("iphone")>=0);
sniffer.blackberry=(agentNow.search("blackberry")>=0);
sniffer.windowsce=(agentNow.search("windows ce")>=0);
var counter=0;
var flag=new Object();
flag.nonMobile=true;
for(var mobile in sniffer)
{
if(sniffer[mobile])
{
switch(counter) {
case 0:
document.write("android<br/>");
flag.nonMobile=false;
break;
case 1:
document.write("series60<br/>");
flag.nonMobile=false;
break;
case 2:
document.write("iphone<br/>");
flag.nonMobile=false;
break;
case 3:
document.write("blackberry<br/>");
flag.nonMobile=false;
break;
case 4:
document.write("windows ce<br/>");
flag.nonMobile=false;
break;
}
}
counter++;
}
if(flag.nonMobile)
{
document.write("Non-mobile or unrecognized device.");
document.write("<br/>");
} |
Before you say anything (or think anything), I realize that this code is about as flexible as a rebar (AKA: reinforcing bar), and if you’re into JavaScript, you can think of 10 ways that this can be done better. However, the goal is to see if this can be refactored into a design pattern. Here’s my plan:
- Set up a dummy Chain of Responsibility that links the different kinds of responsibilities.
- Have each responsibility be actions taken for different kinds of mobile devices or a desktop.
- Use JavaScript objects to do the work of the concrete handlers
However, before I get started on this project, I’d really like to hear from you and even better, see what you can do with this challenge. So between now and the next post on this topic, let’s hear from you! Also feel free to add different kinds of mobile devices such as tablets and other phone OSs.
ActionScript Design Patterns Transcend Changes at Adobe

If you think everyone is heading for HTML5 now, you're nuts!
According to The Economist (Oct 8-14, 2011), in 1993 there were 100 million PCs. By 2008, PCs had topped 1 billion. Many of us tapped into that market one way or another, and some of us came out well rewarded—Adobe certainly did. By 2020 (barely 8 years from now), they expect 10 billion mobile connected devices. In looking at the number consider this: The current #1 Free App on iOS devices is called ‘Hair Plucker’ and who knows how many people bought ‘Angry Birds’, 2010′s top paid for app? Among other apps I saw was a ‘Halloween Mouth’ selling for 99¢–it’s a picture of a mouth you hold up to your face. (How long would that take to create?) Another popular app is not one, but several, that make farting sounds–with prices ranging from free to $1.99.
Latest Update on Flex’s Fate!: Because so many questions about Flex were asked (e.g. Is this the end of Flex?) Adobe posed the following:
Now let’s say, that you create a simple app using a Factory Method. You’ve got 10 billion units out there. We’ll say that you have a ‘Sneezing App’ that makes different sneezing sounds, and it sells for 99¢. If just 1% of 1% of 1% of 1% of 1% of 1% bought your app, that’s $10,000–a half million Indian rupees. If 1 person in 10,000 bought that app, you’d be a millionaire. (The good thing about language-independent apps like the ‘Halloween Mouth’ and ‘Fart Factory’ is that they are language independent.)
20 Billion Mobile Connected Devices Can’t Be Wrong!
I have no idea how many people will be using PCs as we know them. Maybe they’ll go the way of the 5 1/4 inch floppy and all we’ll have is some kind of tablet that we can connect up to the Internet. Development may be done with apps that we rent from a cloud. What is important and key now and later are mobile devices. At this point in time very few Web developers are actively developing apps for mobile devices, and tools like AIR for iOS, Android and Blackberry provide us with a key opportunity.
So, you can be certain that Adobe did not bow out of the Flash-Player-in-the-Mobile-Browser market because they thought it was not going to be a huge market. Look for Dreamweaver to be optimized for HTML5 and some HTML5 development tools. The development tool from Adobe for mobile, though, will be Flash Builder and Flash Pro working with AIR.
A Browser/AIR Mobile Strategy
Keeping in mind that I have nothing against HTML5 and it’s ability to do many things Flash has done for years—Canvas features some great elements and attributes—let’s look at a new strategy for development in Flash (including AS3 and the different flavors of AIR).
First off, if you’ve done much with with mobile browsers, you must have learned they have little to offer, and they are a mixed bag of HTML5 implementation. (The non-mobile browsers are an equal mixed bag as far as having implemented HTML5.) It’s only the mobile browsers that Adobe is no longer supporting. Not too many years ago, there were no mobile browsers; so basically, Adobe is doing what it has always done as far as providing a Flash plugin for the browsers on our computers. It’s just not going to make them for mobile browsers. I developed several apps for iOS, and while most have been simple and small, I was able to use the same programming structures I did for “regular” AS3.
Second, Adobe has been making big strides with Flash Builder and Flash Professional in creating AIR tools for working with mobile devices. This allows us to create ActionScirpt 3.0 apps for mobile devices—forget Web pages. Imagine knocking together an app that does something useful (like calculating the best point in relationship to a parabolic mirror to place a kettle to boil water) that can be used worldwide. Or even a game using some of the little structures we’ve been developing and discussing on this blog that you can sell for 99¢ (or more!). So quit thinking of yourself as just a “Web site developer/designer.” You’re an app developer/designer.
Everyone Runs to HTML5! Not!
Earlier this year I wrote a book (Smashing HTML5) published by Wiley, and one of the chores I encountered was testing the examples against several different browsers, including mobile ones. There was not a lot of compatibility, and most mobile browsers were successful with only a small subset of the HTML5 elements. Over time, let’s hope this improves because if it doesn’t we’ll enter the Second Dark Age of incompatible browsers.
In order to get most of the cooler stuff to work, you need either JavaScript or PHP, and so I included chapters on both. (PHP seems to be more compatible for all browsers than anything else–probably because of the simpler subset of HTML it generates.) I added as much OOP to both as possible, and some of the reviewers didn’t like the fact that it was not more oriented to the DOM or that I didn’t use more procedural examples in the PHP/JavaScript section. What I was trying to do was to write an HTML5 book for 2011 and not 2001, which meant that I used several examples of dealing with a mobile environment. Further, some OOP in JavaScript/PHP is a good thing; so I hope that will move some folks towards structure in both JavaScript and PHP.
However, without Flash in the mix, creating Web apps and pages is frustrating, not because JavaScript and PHP aren’t good programming tools but rather because of browser incompatibility. I’ve got a feeling that to effectively use HTML5 and all of the related CSS3, developers are going to be spending a lot of JavaScript code determining which browser is being used and making the appropriate accommodations. Who wants to sub-code for every possible browser? This includes mobile browsers. My hunch is that they’ll all head for the lowest common denominator, which is probably one of the mobile browsers that is just slightly better than HTML4.
So, I’ve started thinking “Build an App; Not a Web Page.” Let’s hear your thoughts on Adobe’s decisions.
Speed Tweaks: Reuse Objects
When I recycle, I’m doing green. The same idea for functions is equally helpful in avoiding garbage collection. Instead of writing a separate function, reuse one you’ve got. I got the idea from an article by Scott Pertersen, but while working on this post I realized that Scott was talking about something else. He noted that using function objects instead of events cuts down on program allocations. Following that thought, he suggests listening for an event just once. One event handler deals with the event for multiple clients. (Sounds like an Observer design pattern—always a good idea.)
Taking these two thoughts together, I made a single pair of event handlers for multiple objects. That wasn’t Scott’s meaning. He’s pointing out that the fewer events the better; not lots of events handled by fewer functions. However, creating a static method that handles any number of different static properties seemed to be a good idea because both the static method and properties were re-used. (Some other time, I’ll look into how to listen for an event once. It makes sense to do so.)
Static Drag
For now, I’d like to take a look at reusing two event handlers—start and stop drag with mouse down/up. I realize that this doesn’t use any kind of special mobile ActionScript 3.0 (AIR statements to be used in conjunction with mobile devices), and we’ll get to that in further posts. For now, I just want to focus on writing a single pair of static methods for event targets. Using the drag states is simple and explains the idea. (You can download the files if you wish—click the download button.)
![]()

To keep things clean, I created a class that makes shapes that can be used by a direct call. Then, I used a Client class to call the shapes (in Sprite objects) for dragging around a mobile stage. Note that it is flush with static properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package { import flash.display.Sprite; public class ShapeSelect extends Sprite { private static var ball:Sprite = new Sprite ; private static var box:Sprite = new Sprite ; private static var triangle:Sprite = new Sprite ; public function doBall():Sprite { return makeBall(); } public function doBox():Sprite { return makeBox(); } public function doTriangle():Sprite { return makeTriangle(); } //Color: B9121B,4C1B1B,F6E497,FCFAE1,BD8D46 private static function makeBall() { ball.graphics.beginFill(0xB9121B); ball.graphics.drawCircle(50,50,50); return ball; } private static function makeBox():Sprite { box.graphics.beginFill(0xBD8D46,.8); box.graphics.drawRect(10,10,80,80); return box; } private static function makeTriangle():Sprite { triangle.graphics.beginFill(0x4C1B1B,.7); triangle.graphics.drawTriangles(Vector.<number > ([10,20,20,90,150,90])); triangle.graphics.endFill(); return triangle; } } } |
As you can see the public functions return a ball, box or triangle Sprite pulled from three private static functions. No great shakes, but it’s clean and clear. All of the static functions mean that the objects are built in compile-time.
Next, they’re called from a Client class. The MOUSE_DOWN and MOUSE_UP events are called and all objects use the same start/stop drag functions. This reduces the number of methods required, but it is not doing anything for reducing the resources used in calling an event. That I’d like to take up in a future post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package { import flash.display.Sprite; import flash.events.MouseEvent; public class Client extends Sprite { private static var ball:Sprite=new Sprite(); private static var box:Sprite=new Sprite(); private static var triangle:Sprite=new Sprite(); private static var shapeSelect:ShapeSelect=new ShapeSelect(); public function Client() { ball = shapeSelect.doBall(); ball.x = 50,ball.y = 20; addChild(ball); ball.addEventListener(MouseEvent.MOUSE_DOWN,doDrag); ball.addEventListener(MouseEvent.MOUSE_UP,noDrag); box = shapeSelect.doBox(); box.x = 70,box.y = 80; addChild(box); box.addEventListener(MouseEvent.MOUSE_DOWN,doDrag); box.addEventListener(MouseEvent.MOUSE_UP,noDrag); triangle = shapeSelect.doTriangle(); triangle.x = 100,triangle.y = 120; addChild(triangle); triangle.addEventListener(MouseEvent.MOUSE_DOWN,doDrag); triangle.addEventListener(MouseEvent.MOUSE_UP,noDrag); } //All of the event calls use the same two static functions private static function doDrag(e:MouseEvent) { e.target.startDrag(); } private function noDrag(e:MouseEvent) { stopDrag(); } } } |
I tried this out using iOS AIR and when I tried it out in my iPhone, it worked quite smoothly.
Speed Tweaks: Static Objects and Methods

Add ActionScript 3.0 Speed Tweaks to Mobile Apps
When I first started writing ActionScript 3.0 for mobile devices, I wrote it pretty much like I did for desktop or laptop computers. One of the early programs included a simple tween that would move a logo from the middle of the page to the top left corner revealing a center-page main image. Instead of getting a spiffy movement to get the viewer’s attention, on my mobile phone I got a slow-as-mud tween that seemed to get stuck in the middle. (The image to the left shows the logo taking its sweet time moving from the middle to the top of an iPhone.)
Both on this blog and in our book, the focus has been on design patterns and related topics—loose binding, reusability and class/object relationships. The issue of speed has been relegated to the back seat with only occasional references to optimizing speed in programs. The Flyweight, skip-list and a few other posts are among those exceptions. Now, we’re going to look at speed tweaks (and invite you to share your own.) Our first is using static properties and methods.
What’s Up with Static?
The idea of a static property or function is usually one of immutability—unchangeable. Isn’t that that same thing as a constant? In some respects, yes, but it’s more than that. Besides, why is a static object faster? After all, that’s the important consideration for a speed tweak.
At the base of a static object is what is called static memory allocation. Basically, this process occurs during compilation before run-time when the program is executed. Think of it as calling in an order (compile-time) at a take-out restaurant. When you show up at the restaurant, your order is ready. That’s a lot faster than making the order and then waiting around while they’re fixing the order at run-time.
Static objects are something like private accessors and something like CONSTANTS. First, static properties are accessible only through a defining class or when returned by arguments. Second, when immutable values are used when a variable is statically defined, it does not have to be re-defined. In our book in both Chapter 3 (Singletons) and Chapter 6 (Composite) you will find several examples of static variables at work. They are especially popular in use with Singletons, so be careful. (For an unbiased discussion of Singletons, see these posts.)
Static Easy
Static properties are not all that difficult to create. In the following listing, which I created using an Android AIR template, you can see a simple constant literal set as a static property and a static method called from a Client class, which also uses static variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | //Static property and method package { import flash.display.Sprite; public class StaticObject extends Sprite { private static const AS3DP:String = "ActionScript 3.0 Design Patterns"; public function StaticObject() { showStatic(); } private static function showStatic() { trace(AS3DP); } } } //Static variable package { import flash.display.Sprite; public class Client extends Sprite { private static var statObject:StaticObject; public function Client() { statObject=new StaticObject(); } } } |
I tend to think about static variables in the same way as I do private accessors—but for different purposes. I try and use private accessors for encapsulation and forcing myself to write better OOP. For static properties, I just think more speed. Scott Petersen has a good article on these and other issues involving mobile device optimization for iOS, and you should take a look at what he has to say about static objects as well.
Back to Statements and Algorithms: New Wine in Old Bottles

As ActionScript 3.0 grows and changes, we can apply the old design patterns and begin looking for new patters to accommodate some changes.
AIR for Androids, iOS and Blackberry
Currently, the focus of most of the posts on this blog have been design patterns using ActionScript 3.0 with an occasional visit to some interesting structures such as dependency injection and skip lists. Now, a lot of the discussion will shift to newer statements and elements that make up the Flex/Flash family of APis and platforms. In particular you will want to take a look at the AIR 3 reference guide. Herein lie the statements, packages and namespaces that make up a lot of the new features we need to consider. Adobe helpfully marks each AIR class with a little red triangles with balls on the points.
In creating an AIR app, whether for a mobile device or computer, there are differences depending on the hardware device. Once we’ve covered several and created sample examples, we can cast them into design patterns. So, consider this next set of posts to be a temporary detour that will take the knowledge set forward but keep the utility of what has passed.
Removing Decorations: Here Come the Repo Men

Removing Decorations can be Tricky
The 2010 film, “Repo Men” is about a dark future where body parts are purchased much like homes. You get the needed part (like Steve Jobs got his liver) and pay for it with a mortgage. If you fall behind in your payments, the Repo Men come and take it away so that it can be sold to another customer. It turns out that removing a decorator from a component in the Decorator Design Pattern is about as draconian. All along I had imagined it about as simple as removing ornaments from a Christmas tree. Apparently others have issued similar claims, but try and find a decent example, and you’re likely to come up blank. I finally was able to track down an example in O’Reilly Media’s Head First Labs, and it works; sort of. First, though, consider why adding and removing decorations is worthwhile investigating.
Why Removing Concrete Decorations is Important
Now that I’ve been programming madly to get ActionScript 3.0 to work with mobile devices (the iPhone in particular), I’m finding that creating graphic objects is sloooow. The idea behind developing games with patterns like Decorator is that I can take a component and add and remove decorations without having to recreate the object with all of elements that go with it. I can just add and subtract concrete decorators and leave the component as is. This would seem much faster because I’m instantiating less. (Yes, the Flyweight pattern would be another for adding some speed to the process.) Of course you don’t have to be developing for mobile devices; it’s just as handy for computers.
Removing One Decoration Works Fine
I tried out the fix suggested in Head First Labs, and it works dandy. Go ahead and download all the files (they’re two sets in a single zip file; one for removing a single decorator and another for multiple) and then click the Play button to see how a single removal works:

![]()
All downloads are now on the University of Hartford’s MWDD Download Page. Select the last window to the right (ActionScript 3.0/Flash) and click on the bottom link and then click the Download button.
donE
The movement to the left and right was to show how the decorated component is a “single object,” but even that is a bit of fakery. Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package { import flash.display.Sprite; import flash.errors.IllegalOperationError; //Abstract class. Do not instantiate directly //Extend the class for concrete child classes public class Component; { protected var armor:Sprite; public function getarmor():Sprite { return armor; } //remove public function removeArmor():Component { return this; } } } |
In the Component abstract class, you can see the addition of a single added method, removeArmor(). What you may be scratching your head about is why a Component object is returned. That’s what’s decorated, no? Shouldn’t it be zapping a decoration? What the function appears to be doing is stripping the component of all decorations. But let’s move on to the Decorator, both abstract and concrete: Read more…






Bill Sanders
Recent Comments