Archive

Archive for the ‘Design Patterns’ Category

From ActionScript 3.0 to JavaScript Chain of Responsibility: Part II The Help Desk

January 4, 2012 5 comments

corjs

JavaScript can do Design Patterns

A JavaScript Chain of Responsibility

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:

helpdesk

Figure 1: JavaScript Chain of Responsibility Help Desk

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:

?View Code JAVASCRIPT
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:

?View Code JAVASCRIPT
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:

?View Code JAVASCRIPT
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.

?View Code JAVASCRIPT
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>&nbsp;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.

Share

From ActionScript 3.0 to JavaScript Chain of Responsibility: Part I

December 26, 2011 1 comment

After Mom, Ask Dad, and then the Dog

After Mom, Ask Dad, and then the Dog

Just Follow the Chain of Responsibility

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:

<em><strong>Figure 1: </strong> Chain of Responsibility Pattern</em>

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.

?View Code ACTIONSCRIPT
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…

Share

Can JavaScript Create Design Patterns?

November 28, 2011 7 comments

Face the Facts: We've got to deal with Mobile

Face the Facts: We've got to deal with Mobile

Ever since Adobe announced that they’d no longer be making a Flash player for mobile devices, I thought that it’d be a good idea to have some kind of filter to distinguish between desktop browsers and mobile ones. On this blog, I’d like to introduce a topic that is related to the continuing efforts to build apps and Web pages with ActionScript 3.0 using OOP and Design Patterns. The topic is a language: JavaScript.

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:

?View Code JAVASCRIPT
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:

  1. Set up a dummy Chain of Responsibility that links the different kinds of responsibilities.
  2. Have each responsibility be actions taken for different kinds of mobile devices or a desktop.
  3. 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.

Share

Back to Statements and Algorithms: New Wine in Old Bottles

October 23, 2011 2 comments

As ActionScript 3.0 grows and changes, we can apply the old design patterns and begin looking for new patters to accommodate some changes.

As ActionScript 3.0 grows and changes, we can apply the old design patterns and begin looking for new patters to accommodate some changes.

Chandima and I have exhausted the set of design patterns that the Gang of Four published in 1995, and we even started looking at the new design patterns developed for parallel programming in Parallel Programming with Microsoft.NET: Design Patterns for Decomposition and Coordination on Multicore Architectures (2010), whose authors include Ralph Johnson, one of the original GoF. The problem with that route (at this time) is that C# has a bunch of statements for parallel programming and ActionScirpt 3.0 does not. There’s a lot edging its way to the front of the shelf as developers and Adobe work on Flex, Flash and Flash Builder. One technology, Pixel Bender provides a way to work with both the CPU and GPU. Pixel Bender has been around for a while, but it represents a feature of the future—accessing multiple processors from ActionScript 3.0.

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.AIR 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.

Share

Removing Decorations: Here Come the Repo Men

October 2, 2011 1 comment

Removing Decorations can be Tricky

Removing Decorations can be Tricky

We’ve Come to Take Back Your Kidney

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:
kilroy
play

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:

?View Code ACTIONSCRIPT
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…

Share
Categories: Decorator

ActionScript 3.0 Flash Builder App in Apple iOS: Decorator and State

September 5, 2011 4 comments

Change orientation with device position

Change orientation with device position

Decorator and State Patterns in Mobile Game Development
While I’m trying to find the best graphic tool to use in conjunction with mobile devices and ActionScript 3.0, I’ve decided to stick with wholly programmed images. (I’m a better programmer than artist, but my images do not improve because they’re programmed.) For this example, I used the ActionScript Mobile Project option in Flash Builder 4.5.1. If you’re using Flash Pro 5.5, you can use the same code by selecting AIR for iOS from the Flash main start-up menu. With both, everything is pure ActionScript 3.0—none of the drawing tools, components or other gizmos available in either FB or FP are employed—código puro in both. Click the button below to download the files for Flash Builder. (I also included the files for Flash Pro; so no one is left out.)
kilroy

Reminder: We’ve placed all of the downloads on the University of Hartford’s Multimedia Web Design and Development download page. Just select the bottom on the ActionScript 3.0 files and click the download button.

Flash Builder Tip: First create an ActionScript Project so that you can test it as you develop. Once you have it all developed, create an ActionScript Mobile Project and just copy and paste the files from the AS Project.

Re-Decorating

In this first part all I want to do with this mobile game is to build and decorate the warrior and put it on an iOS mobile device using Flash Builder. The mechanics are very similar to previous posts on using the Decorator pattern to arm a character (See here and here.) Figure 1 shows a file diagram of the Decorator implementation:

<em><strong>Figure 1:</strong>Decorator File Diagram</em>

Figure 1:Decorator File Diagram

Since this thing is going to be in pure code, we need to create a “warrior” in code, which was not done in the previous posts linked above. So outside of the pattern, we need a graphic image, as provided in the following code:

?View Code ACTIONSCRIPT
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
package
{
	import flash.display.Shape;
	import flash.display.Sprite;
 
	public class BuildWarrior extends Sprite
	{
		private var head:Shape=new Shape();
		private var torso:Shape=new Shape();
		private var lftArm:Shape=new Shape();
		private var rtArm:Shape=new Shape();
		private var lftLeg:Shape=new Shape();
		private var rtLeg:Shape=new Shape();
 
		public function assemble():Sprite
		{
			this.addChild(makeHead());
			this.addChild(makeTorso());
			this.addChild(makeLftArm());
			this.addChild(makeRtArm());
			this.addChild(makeLftLeg());
			this.addChild(makeRtLeg());
			return this;
		}
 
		private function makeHead():Shape
		{
			head.graphics.lineStyle(1,0x6F74B3);
			head.graphics.beginFill(0x6F91A6,.50);
			head.graphics.drawRect(30,17,10,3);
 
			head.graphics.lineStyle(0.25,0x0066ff);
			head.graphics.beginFill(0x035AA6,.40);
			head.graphics.drawCircle(35, 7,10);
			head.graphics.lineStyle(1,0x6F74B3);
			head.graphics.moveTo(30,6);
			head.graphics.lineTo(34,6);
			head.graphics.moveTo(36,6);
			head.graphics.lineTo(40,6);
			head.graphics.moveTo(32,12);
			head.graphics.lineTo(38,12);
			graphics.endFill();
			return head;
		}
 
		private function makeTorso():Shape
		{
			torso.graphics.lineStyle(1,0x6F74B3);
			torso.graphics.beginFill(0x6F91A6,.50);
			torso.graphics.drawTriangles(Vector.<number>([10,20, 60,20, 35,90]));
			torso.graphics.endFill();
			return torso;
		}
 
		private function makeLftArm():Shape
		{
			lftArm.graphics.lineStyle(1,0x6F74B3);
			lftArm.graphics.beginFill(0x6FB3A7,.75);
			lftArm.graphics.drawRect(10,20,10,40);
			lftArm.graphics.drawRect(10,60,40,8);
			lftArm.graphics.endFill();
			return lftArm;
		}
 
		private function makeRtArm():Shape
		{
			rtArm.graphics.lineStyle(1,0x6F74B3);
			rtArm.graphics.beginFill(0x6FB3A7,.75);
			rtArm.graphics.drawRect(50,20,10,40);
			rtArm.graphics.drawRect(51,60,8,40);
			rtArm.graphics.endFill();
			return rtArm;
		}
 
		private function makeLftLeg():Shape
		{
			lftLeg.graphics.lineStyle(1,0x6F74B3);
			lftLeg.graphics.beginFill(0x6FB3A7);
			lftLeg.graphics.drawRect(23,70,12,45);
			lftLeg.graphics.drawRect(24,115,10,45);
			lftLeg.graphics.endFill();
			return lftLeg;
		}
 
		private function makeRtLeg():Shape
		{
			rtLeg.graphics.lineStyle(1,0x6F74B3);
			rtLeg.graphics.beginFill(0x6FB3A7);
			rtLeg.graphics.drawRect(36,70,12,45);
			rtLeg.graphics.drawRect(37,115,10,45);
			rtLeg.graphics.endFill();
			return rtLeg;
		}
	}
}

All of the concrete decorators similarly implement coded graphic representations. Of course, all of these are “outside” of the design pattern but are useful to see in the contact of the pattern.

The Client

In the actual mobile client, you begin with a super(); call and support for auto orientation in the iOS device. The code is automatically generated:

?View Code ACTIONSCRIPT
1
2
3
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

I tossed out the super(); call, and generated the following client:

?View Code ACTIONSCRIPT
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
package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
 
	public class MobileDecState extends Sprite
	{
		private var warrior:Component=new Warrior();
		private var warriorSpirit:Sprite=new Sprite();
		public function MobileDecState()
		{
			warriorSpirit.addChild(warrior.getarmor());
			warriorSpirit.x=50,warriorSpirit.y=50;
			addChild(warriorSpirit);
 
			warrior=new DecBodyArmor(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecShield(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecHelmet(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecParticleCompressor(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			// support autoOrients
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}
	}
}

Publishing for Mobile

For some reason, more steps are involved in publishing for Flash Builder than Flash Pro. However, once you have your certificate (it has a .p12 extension) and your provisioning file created using the tools available to Apple developers; it’s pretty simple. If you don’t know about the Apple iOS developer program for both Windows and Mac users, you need to go there first.

Here’s how to publish using Flash Builder: (Download the Beta version/update of Flash Builder 4.5.1. While you’re at it, download the beta version of Adobe AIR 3.)

1. Open a New > New ActionScript Mobile Project (Figure 2)

<em><strong>Figure 2: </strong> Open a New ActionScript Mobile Project </em>

Figure 2: Open a New ActionScript Mobile Project

2. Specify your target platform as Apple iOS with Automatically reorient selected and click Next. (Figure 3)

<em><strong>Figure3: </strong> Mobile Settings </em>

Figure3: Mobile Settings

3. Click the Platform Setting and select Platform and Target devices (Figure 4)

<em><strong>Figure 4: </strong> Specify Platformsettings </em>

Figure 4: Specify Platformsettings

4. Build Paths provides the opportunity to add SWC folders or a project. Figure 5 shows using the default settings.

<em><strong>Figure 5: </strong> Include additional or different paths if requires </em>

Figure 5: Include additional or different paths if requires

5. The next step in creating your app will not come until you are finished coding it all. Then when you press the green arrow (Run) button at the top, you will begin the Run Configurations sequence. Figure 6 shows the On device radio button selected. You are likely to see some red circles with white ‘X’s in them, but don’t worry. If there’s one next to the Packaging setting click the [Configure] link.

<em><strong>Figure 6: </strong> Run Configurations </em>

Figure 6: Run Configurations

6. Set the Certificate and Provisioning file. Both of these should be ready using the software that the Apple iOS Developer program provides. Use the Browse buttons to locate yours. (These cannot be generated using Adobe software.)

<em><strong>Figure 7: </strong> Setting Certificate and Provisioning files </em>

Figure 7: Setting Certificate and Provisioning files

Once the certificate and provisioning file are set, click the Apply button and then click OK.

7. If all has gone right you will see the Packaging Completed window shown in Figure 8. At this point you will have to open iTunes on your computer, and make sure that your mobile device is connected to your computer. You will need to locate the .ipa package and drop it into the iTunes library. It’s easiest to just click the (Reveal package in Finder) to get the .ipa package.

<em><strong>Figure 8: </strong> Completed Window </em>

Figure 8: Completed Window

8. Figure 9 shows the bin-debug folder opened with the .ipa package. Be sure that the Apps window on your iTunes library is selected and drag the .ipa package into the iTunes library.

<em><strong>Figure 9 </strong> Drag .ipa package into iTunes Apps Library </em>

Figure 9 Drag .ipa package into iTunes Apps Library

9. The final step requires that you select the connected device (shown right above Little Richard Greatest Songs in Figure 10 ) and then find your new app in the Sync Apps window. Be sure to check the box next to the app. Then click the Apply button. Clicking the Apply button will then begin the Sync process. Once it is finished you should see the icon.

<em><strong>Figure 10: </strong>Adding the app to an iOS device</em>

Figure 10: Adding the app to an iOS device


When you click the icon on your iOS mobile device, you will see the image shown at the top of this post. If you turn your device, the object will re-orient itself to the object’s orientation.

Adding the State Design

With this and the previous posts for mobile devices, you’ve seen that design patterns work well with mobile app development. All of the advantages found in design pattern development for computers can be found in creating applications for mobile devices.

In the next post, this process will be continued by adding a State pattern to the app to create a game. If you don’t have a mobile device, you can use the same coding for making the app for your computer.

Share
Categories: Decorator, Mobile, State

ActionScript 3.0 Design Patterns and iOS: A New Home for Apps

August 15, 2011 1 comment

Make Your Own Apps with Design Patterns

Make Your Own Apps with Design Patterns

It’s Easy Once You Get Your Certificate and Provisioning Profile

Having finally got my magical combination of permissions set up just so, the process began coming fairly easily. The problem is not Adobe, but rather getting the files from Apple just right. Once you get the files, you can use them over an over. One is a certificate file with a .p12 extension, and the other is a provisioning file. It looks like a lot of people are having the same problem because when I finally found a solution on the Web at StackOverflow several other developers indicated (with heart-felt thanks) that they were encountering the same problem. (The solution that worked for me was to start over and delete all provisioning profiles and login keychain.) So if you got your Apple iOS Developer ticket ($99 or free to University students/faculty), that’s just the first part. The next part is to hook up your iOS device (mine is a 3S iPhone) and using the Xcode development tools, go through a process that generates the files you need. The following image shows what these little gems look like. If you put those two files in with your AIR iOS files, it’s a piece of cake. (Go ahead and download the files as well.)

Same files can be used with different apps

Same files can be used with different apps


kilroy

Apple provides videos and a whole slew of tools and aids, and if you follow the instructions, you should be able to develop the right files. (Sad experience had led me to suggest that you take your time and follow instructions carefully.) Anyway, whether you get the certificate and provisioning files on the first time or whether you struggle like I did, once you’ve got them; they’re good for about four months. You can develop on either a Mac or Windows PC and re-use the same files on different apps. (I haven’t gone through the process that Apple has for getting an app in the App Store; so you’re on your own in that department.) The image on the right is a screenshot taken with an iPhone:

Animated tween, text and graphic

Animated tween, text and graphic

Step-By-Step

This section walks you through the process of working with a Flash Pro project set up for use with iOS. In the previous post on iOS, the sample project was to create banners that can be used in a Factory Method context by loading external .SWF files. On the iPhone, that didn’t work. The problem seemed to be the mobile device’s inability to grab the external .SWF files even though, the .SWF files were included in the General settings for the Included files window. So, using the same tweens, I created MovieClips and put them in the Flash Pro library and then set them up as classes. Then in the concrete product files, I just instantiated classes with the tweens instead of loading external .SWF files, and the rest of the program was unchanged. (That is where design patterns really shine—easy to make changes.)

Okay, now to step through the process. This was all done using AIR 3.0, Flash Player 11 public betas on a iMac running the new Lion OS. After you open a new AIR for iOS and write all of your code and add any graphics and text, the first step is to select the FLA file, make sure that nothing is selected on the stage and then click the little wrench icon next to the Player selection where it should indicate ‘AIR for iOS.’ That will open the AIR for iOS Settings window as shown in Figure 1:

<em><strong>Figure 1:</strong> General Settings of AIR for iOS</em>

Figure 1: General Settings of AIR for iOS

For getting started, choose Full screen instead of Auto orientation. Use the CPU for the Rendering processor, specify your device and choose the Standard resolution. The included files will be an .SWF and .XML file. Leave those alone, and for this app, you do not need to add any others.

For this next step, you’ll need both the certificate and provisioning files in the same folder with the other class files. So if you haven’t created those files and linked them to the device you’re testing it on; do so now. The click the Deployment button next to the General button at the top of the AIR for iOS Settings window. Figure 2 shows the deployment settings:

<em><strong>Figure 2:</strong> Deployment window</em>

Figure 2: Deployment window

The password for the certificate is the one you entered when you created the certificate—not one associated with your computer. Use the search folder to find your Provisioning profile file. The App ID is the name you gave your initial FLA file—I’m in the habit of calling all of mine “Client,” but now I’ve got to think about what users will see on their mobile device..

This post does not get into the iOS deployment beyond the local development stage. So, select the “Quick publishing for device testing” or “Quick publishing for device debugging.” I selected the former because I chose to do the debugging using the standard Flash tools. After all I went through to get the certificate and mobile provision files to work right, I wasn’t about to tempt fate just yet and do more than the minimum.

This final step is fun. You can easily create your own iOS icon. Here’s what you need to do to get started:

  1. Create a square image with your logo or some symbol you want to use to identify you application. Save it as a .PNG file. (In the image at the top of this post, you can see the two application icons using the Sandlight logo.) Be sure that the image has equal width and height.
  2. Save three images in sizes 29 pixel square, 57 pixel square and 512 pixel square. Depending on the mobile device, you may want to create other sizes as well. I started off with the Adobe Illustrator version and saved each size as a PNG file.
  3. Place the three image files in a folder named “icons” and place the icons folder in the directory where you are creating your mobile app.

In Figure 3, you can see the preview window showing the image used for the application described in this post.

<em><strong>Figure 3:</strong> Assigning icons for app image</em>” title=”Fig3″ width=”500″ height=”694″ class=”size-full wp-image-6158″ /><p class=Figure 3: Assigning icons for app image

Be sure to click each icon size for each of the three sizes and load the URL (icons/iconXX.png) before you click OK. Note also that two of the icons are settings for iPads, and so if you have an iPad, create image files for those as well.

Installing your iOS on your Mobile Device

Now you’re set to Publish your files required for an iOS mobile app. When you click “Publish” you will find that it takes a while to process everything. Once you’re finished, you will see all the files generated for your iOS device. Figure 4 shows the files you will see—including the all-important .IPA file.

<em><strong>Figure 4:</strong> Files used and generated</em>

Figure 4: Files used and generated

As you can see in Figure 4, one of the files is named BannerFactory.ipa. That is the file that will install your app onto your iOS mobile device. Connect your iPhone or iPad or iWhatever that runs on iOS, and double-click the IPA file and it will upload your app into the iTunes Apps folder. (On your iTunes, click Apps in the LIBRARY folder, and you should see your new application as shown in Figure 5.)

<em><strong>Figure 5:</strong> iTunes Apps folder</em>

Figure 5: iTunes Apps folder

If you see your application icon and file, you’ve been successful—up to this point. The last step is to install your app onto your mobile device. The final step is to select your device and then check your application Sync. Figure 6 shows iTunes with your application selected (checkbox) and ready for Sync.

<em><strong>Figure 6</strong>App set for installing in iPhone</em>

Figure 6: App set for installing in iPhone

Note in Figure 6 that the iOS device is selected under DEVICES in the left panel and that the new application (BannerFactory) has a check next to it. Click the Sync button (or Apply and then Sync) and if you have your device properly identified, you will see your icon and app on your mobile device.

Share

Mobile Banner Factory for iOS

Animated Banners are easy with Flash

Animated Banners are easy with Flash

Surprise your Users!

I’ve never been a big animated banner fan. They are contrary to everything I know about good Information Design. However, done right, they can add pizazz to a page. The trick is to make sure that after the banner has performed its show once to stop it. Like a twice told joke; the animation is only interesting the first time. After that, the banner needs to serve as a branding decoration. Further, you can make your opening page a bit more interesting by having multiple banners randomly appear. Every time the visitor opens the mobile app, he/she can look forward to seeing a different banner appear. Using a Factory Method design pattern, that can be easy to create and (more importantly) update. In this post I want to get set up with a simple (but handy) Factory Method design pattern for calling up different banners; so it can be regarded as a beginner’s introduction to the Factory Method pattern.

The plan is to walk through an iOS implementation of ActionScript 3.0 in both Flash Pro and Flash Builder. However, first I want to get the design pattern squared away, and then we can provide total focus on the iOS issues. Further, if you would rather create an app using Android or Blackberry, you can just use the code and design pattern is this post and forget about the subsequent iOS posts that use the design pattern shown in this post. I did not provide the downloads for this post because I used a generic ActionScript 3.0 implementation, and so you can just cut and paste the code in the listings that are part of this post. (The downloads for the iOS implementations will be provided in subsequent posts.) To get an idea of what this does, click the Play button and refresh the HTML page to see how one of two animated banners appear.
play

The Factory Method in an iPhone

Here, I want to use the Factory Method, but I’m not going to explain it (again.) That’s been done here in our blog and in Chapter 2 in our book. Here I just want to explain how it is used to generate random banners for an iPhone (or whatever other mobile or non-mobile device you want to use it with.) The factory (Creator) instantiates any number of concrete Product instances. As implemented in this example, each concrete product requires a concrete factory instance. I added a helper class, RandomSelector to generate random numbers in a range. The Client pulls in a random value (between 0 and 1) and then using a switch statement calls a method to request a SWF file to play an animated banner. (Those among you who want to create your own SWF banner and pull it up instead of the ones you see in the example can do so easily.) Figure 1 shows the File Diagram of the Factory Method as used in this implementation to provide an overview.

<em><strong>Figure 1:</strong> File Diagram of Factory Method Implementation</em>

Figure 1: File Diagram of Factory Method Implementation

As you can see in Figure 1, the Client makes the requests through the ICreator (factory) interface, the concrete factories instantiate the concrete products, which load the SWF files for display. The RandomSelector class sits off by the side providing a random value.
Read more…

Share
Categories: Factory Method, Mobile

Flash Builder Mobile ActionScript 3.0 Design Pattern

Flexible Design Pattern Re-used with Flash Builder Development

Flexible Design Pattern Re-used with Flash Builder Development

Easy Update

A couple of days ago, we had an example for beginners creating a mobile application using Flash Professional. We used an Android example because everyone can get the tools they need for emulating an Android. (By the way, partnering up with Google-Android and Flash was a brilliant move by Android. Being an “Apple Guy,” I thought I’d be doing nothing but apps for my iPhone and iPads; however, Android made it a lot easier to develop apps for Android using some kind of ActionScript 3.0 development tool, and Blackberry’s not far behind. So I am very happy to know that iOS is now available, but they’ll just have to wait their turn for a beginner’s post.) As promised, I wanted to create a beginner’s example using Flash Builder. This example uses the same Strategy Pattern as the Flash mobile tutorial. However, as you will see, there are some key differences when dealing with Flash Pro and Flash Builder. Also, I hope you see that a very different logo (FB instead of Sandlight) and text. All that was changed for this difference was swapping the image used for the logo and the text in the external text file. Also, I had to change some settings in the BringText class, but that too was easy and didn’t upset the program. Why? Because it was a design pattern!

Stepping Through Flash Builder Mobile

This is going to be the same walk-through with Flash Builder as with Flash Pro but with a few differences. The Flash Builder work flow is slightly different, but you will find more similarities than differences. Before we get going download Flash Builder 4.5.1. (You can use the 30-day free trial version.) You can probably work with FB 4 with all of the updates, including the Android SDK, but everything in this example was done with FB 4.5.1. (If you are a student or faculty, you can get a free educational version of FB if you contact Adobe with your student or faculty ID. Faculty can get it free for their classrooms and labs as well.) Install to the defaults. Go to Adobe Labs download and install both Adobe AIR 3 (beta) and Adobe Flash Player 11 (beta) and let’s get started:

First, open Flash Builder and select File > New > ActionScript Mobile Project. (Note: You will find both a Flex Mobile Project and an ActionScript Mobile Project; be sure to select ActionScript Mobile Project.) In the Project name window, name the project FBmoStrat as shown in Figure 1 :

<em><strong>Figure 1:</strong> New ActionScript Mobile Project window</em>

Figure 1: New ActionScript Mobile Project window

I used the default location and the default SDK, which was Flex 4.5.1. Click Next.

Second, when The Create an ActionScript Mobile AIR Project window appears with the Mobile Settings tab selected, you will see that all Target platforms (Apple iOS, BlackBerry Tablet OS and Google Android) are checked as shown in Figure 2.

<em><strong>Figure 2:</strong>Initial Create Window</em>

Figure 2:Initial Create Window

Third, uncheck both the Apple iOS and BlackBerry Tablet OS. When you do that, the Permissions for Android appear as shown in Figure 3:

<em><strong>Figure 3: </strong> Android Permissions</em>

Figure 3: Android Permissions

Be sure that the Platform is Google Android and that the only permission checked is INTERNET. The default is to Automatically reorient the screen in the Application settings. Leave that default checked and click the Next button.

Fourth, in the Build Paths step, you will see a set of default selections you can leave alone except for the Main application file that you want to change from FBmoStrat.as to Client.as. Figure 4 shows the step correctly configured:

<em><strong>Figure 4:</strong> Build Paths step</em>

Figure 4: Build Paths step

If your Build Paths steps looks like Figure 4, click Finish. You should see the following script automatically generated:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
 
	public class Client extends Sprite
	{
		public function Client()
		{
			super();
 
			// support autoOrients
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}
	}
}

The Stage Align and StageScaleMode built-in ActionScript 3.0 classes will help align the application when it is turned in different directions. The super() method invokes the parent class Sprite. You will be leaving the constructor function as is but add more materials for the Client class. Before doing that, go ahead and test the problem and download all of the files with the buttons below:
playkilroy

You still will need to test the file from Flash Builder and contend with one last set of settings. So gather up all of the files and read on before testing.

Read more…

Share
Categories: Mobile, Strategy Pattern

Beginning Mobile ActionScript 3.0 Design Patterns with Flash

ActionScript 3.0 Design Patterns in Mobile Apps

ActionScript 3.0 Design Patterns in Mobile Apps

Get Your App Up!

The very first mobile app I want to build is one that I can give away to promote my company or my clients’ companies. Yes, I’d like to make lots of money with a mobile action game like Angry Birds, but in order to get started, I want something that I can easily update and change. It seems like every time I check my phone apps, I’ve got updates. What is one of the main features of Design Patterns? Easy updates! So, if you want to create mobile applications in ActionScirpt 3.0 that are easy to update, you’ll find design patterns your BFF!

This first one is built with Flash CS5.5. If you do not have Flash CS5.5; download the 30-day trial version. If you’re using Flash Builder, use FB 4.5.1. or download the trial version. (I hope to have a FB tutorial using this same example later in the week. In the meantime, take a look at Christian Peters’ mobile example for building an app using design patterns with Flash Builder.)

This first example uses a Strategy pattern with algorithms for loading external images (or .SWF files) and text. That is exactly what I need for a mobile app promoting my company. With the image loading capability, I can load my logo and any images that show off products and services. The concrete text strategy loads up data from external text files. So this ought to be the easiest app to update imaginable!

Easy Android

I was going to start off with an iOS example, but I realized that most of you probably didn’t want to shell out the $99 developer fee required by Apple for iOS development. So, instead I decided to use an Android example that you could test using an Android emulator. To get started, go ahead and download the source code and see what the app displays:
playkilroy

All of the Downloads have been moved to the University of Hartford’s Multimedia Web Design and Development Program page. The last entry under “ActionScript 3.0/ Flash” should have what you want. (I’m still working on it to include a short description of each entry–it’s in the database; just not on the screen).

When you run it, you will quickly see that a logo and block of text pops up. That’s it. Swap out your own logo and texts, and you’re in business. You can change any of the parameters in the BringText concrete strategy class to alter the text appearance, it’s placement and other features to suite your own tastes or business brand.

Starting from Scratch

Since this is a first time experience for beginners and mobile (which may include experienced ActionScript 3.0 programmers), we’ll step through the set-up beginning with the FLA file. So read on through the following steps:

Read more…

Share
Categories: Mobile, Strategy Pattern