Archive

Archive for June, 2011

PureMVC Goes Mobile 1: MVC-driven & ready-to-compile Mobile Application with the Flex Framework! by Christian Peters

Optimizing Mobile Apps with Design Patterns

Optimizing Mobile Apps with Design Patterns

Gentle Readers: Every now and then Chandima and I have a guest post. In this case, Christian Peters who maintains a blog at http://digitale-avantgarde.com was kind enough to translate his post from German into English. (For those of you who would prefer the original German version, visit Chris’ site.) Because of the size of the post, we’ve had to divide it into two separate posts. The second half of the post will be available next week. We and Chris would appreciate your comments. Click the download button to get the entire code:
kilroy

PureMVC Goes Mobile

Let’s build a cross-platform compatible, MVC-driven & ready-to-compile Mobile Application with the Flex Framework!
A year ago, finding people who bet serious money on Flash missing a connection to the mobile world was an easy task. This is no longer the case nowadays. Adobe has introduced an iOS Compiler and AIR for Android & Blackberry Playbook. With the latest release of Flex SDK 4.5.1, the average Flash-Coder is transformed to a crossplatform-ready mobile developer. Amazing times. Let’s look at how to adjust the Standard Port of the famous PureMVC Framework to be mobile-ready! The Flex SDK ships with an integrated Navigation for Mobile Views, the ViewNavigator. There is an excellent introduction to the topic, that can be found here, but I’ll give a brief overview about the concept:

Mobile Applications – especially on Smartphones – are restricted in a very important feature: Space. If you adapt a Web app to mobile, you’ll typically have much more views because you have to present the same content on smaller displays. Flex comes to the rescue by introducing the ViewNavigator. The ViewNavigator is a container, that holds references to the available views and makes navigation between them easy. You can imagine it as an array – where the view at the zero index is visible & active. It’s not a coincidence that the ViewNavigator has array-esque methods like popView() or pushView()!

The ViewNavigator is a nice way to handle views, because it’s an easy way to navigate through an app: Every view holds a reference to the ViewNavigtor – the navigator property – and can forward the application to another view on demand.
Well, it’s not all roses with the ViewNavigator! A view has its own control-mechanism as property – while it should be vice versa. Another downside: The registering and instantiation of views are becoming tasks of Flex, while you normally want to handle those tasks in your infrastructure framework of choice! Mine is PureMVC. I want to show you a way to hook PureMVC to the registering process of the ViewNavigator to build nicely decoupled applications for the mobile world. Some experience with PureMVC is recommended, but I’ll give you a quick …
Read more…

Share
Categories: Mobile, PureMVC

We Need to Talk: Should We Take AS3 DP Mobile?

Design Pattern Development on Mobile

Design Pattern Development on Mobile

What a Difference a Year Makes

A little over a year ago we posted a lament about Apple freezing Flash/ActionScript 3.0 out of their mobile market. In re-reading that post, I was surprised by how prescience some of the comments were. HTML5′s implementation would be all over the map and the debate about H.264 vs. VP8 is as heated as ever. More importantly though, rather than sitting on their hands and wringing their crying towel, Adobe made adjustments to Flash (Both Builder and Pro) and ActionScript 3.0 to deal with the new realities. The recently released Flash Builder 4.5.1 and AIR 2.7 can deal with the most popular mobile protocols.

I realized that we recently began adding posts on parallel programming and got off to a roaring start, but interest waned in that topic as some of the readers realized that AS3 didn’t have the kind of programming resources that other languages had (such as C#) and we were sort of working with a DIY version of parallel programming. I believe that in the next version of AS3, we may be seeing classes where we can directly process multi-threaded programs. Likewise, we began doing Design Patterns and OOP for Beginners, and we’ll continue with those posts.

The idea of adding posts on mobile development involves two issues. First, creating apps for mobile devices is a topic unto itself due to the protocols involved. Second, some new classes in AS3 are specifically for either AIR and/or mobile devices (The new CameraRoll class is an AIR/Mobile class.) So we may have some examples that would be awkward for non-mobile developers. However, we’d try to keep things more universal by suggesting non-mobile alternatives. This is not a proposal to shift to mobile-only AS3 design patterns. Rather it is a proposal to ease into a combined mobile/non-mobile Flash set of examples using design patterns.

Obviously, we’ll need some basic starting points for mobile development, primarily in Android and iOS formats, but we’re pretty new at mobile development ourselves; so it will be in baby steps. Besides, books are becoming available. Véronique Brossier’s book, Developing Android Applications with Adobe AIR: An ActionScript Developer’s Guide to Building Android Applications, (sample chapter) and Matthew David’s new book, Flash Mobile, are resources available for getting up to speed with mobile Flash and ActionScript 3.0.

Anyway, we’d like to get your feedback. Should we start including mobile examples? Yes or No? Use the comments section to share your thoughts.

Share
Categories: Mobile

What if ActionScript 3.0 had no Conditional Statements? : Part I

Think in Non-Linear Concepts

Think in Non-Linear Concepts

On a couple of occasions, we’ve discussed working without conditional statements. You may recall that both the Strategy and State design patterns have no conditional statements, and so the idea isn’t particularly new. The issue came to mind when I was unraveling a PHP program that had nested conditional statements used in pulling out table data. Even though they seem to crop up like weeds everywhere, nested conditionals and loops represent poor practices . (Dave Shuck’s solution for refactoring nested conditionals is worth a look.)

Other than the fact that nested conditionals can create the worst kind of object binding as each condition sends the program further down the binding rabbit hole, we seem to really need them for working out certain kinds of problems. For example, in a visual game scenario, the user may be faced with choices. Suppose the game state is a crossroad where the player must choose to go North, East, West or South (NEWS). Alternatively, the choice may be video perspectives of different directions. Any one of the choices carries with it a whole set of other states, conditions, capabilities and properties.

One way to handle this kind of choice is with a conditional statement. The following shows two things. First, it shows that when a direction is selected, it typically has more than one thing being affected. (The more than one thing is furnished by “Everything else.”) Second, the binding for each is represented by the conditions within each conditional. (You could do the same thing with a Switch statement, but the binding wouldn’t change.)

?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
package
{
	import flash.display.Sprite;
	public class NEWS extends Sprite
	{
		private var newsArray:Array = new Array("north","east","west","south");
		private var dir:Object;
 
		public function NEWS()
		{
			for (dir in newsArray)
			{
				if(newsArray[dir]=="north")
				{
					trace("Hellloo Siberia");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="east")
				{
					trace("Visiting Bejing");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="west")
				{
					trace("Dude! You made it!");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="south")
				{
					trace("¡Recepción a la Argentina!");
					trace("Everything else....");
					trace("");
				}
			}
		}
	}
}

That certainly can solve the issue of generating different responses from different object properties. It’s compact and saves ground-fills of wasted bits. It illustrates a common method of dealing with multiple options. The loop iterates through the object, and each iteration is examined by four conditional statements.

Unconditional Programming

Let’s go back to the NEWS example, and instead of having trace statements representing different directions, this next example uses short videos pointing in different directions. (I live in the woods so the videos are fairly woodsy—but they show the four points of the compass—honest.) I want to make an app with four buttons that plays a video pointing in the selected direction. Plus, I don’t want to use any conditional statements. (Easier than you think.) Click the Play and Download buttons to see a working example and get the code and videos.
playkilroy

In the next section where we examine the code you will see two things: No conditional statements and a non-linear solution. The user has several choices, and simply by making a choice she/he goes directly to the object desired—a directional video.
Read more…

Share

The Warrior's New Clothes: Using AS3 in Flash Builder to Create Sprite Graphic Classes

Code your own Sprite classes

Code your own Sprite classes

Sprite Classes in Code

When I’m working on an example, I’ll use a combination of Flash Pro and Flash Builder. However, using Flash Pro, all of my drawings are in the Flash Library and may not be accessible to Flash Builder users. Besides, my drawings are pretty simple composed of basic shapes—rectangles, circles and triangles. These images are transformed into Sprite classes in the Symbol Editor of Flash Pro, and the type is changed from the default MovieClip to Sprite. If I coded the images as Sprites using ActionScript 3.0, the Flash Builder users would be able to more easily use them and the Flash Pro users could use them with equal ease.

Let’s face it, my graphics are not going to get any better whether I code them or draw them; so why not code them? So that’s what I’ve done. In the previous post on the Decorator design pattern for beginners, I had three graphic “armor” pieces that were used with concrete decorator classes. All I’ve done for this mini-post is to provide the “armor” sprites as pure code. From now on when I have a Sprite image, I’ll just code them up in ActionScript 3.0 as Sprite classes and make it easy for everyone. Here’s the Shield, BodyArmor and Helmet classes: (Next page.)
Read more…

Share

Well-Armored Warrior:ActionScript 3.0 Decorator for Beginners

Decorator Adds Changes without Changing the Object

Decorator Adds Changes without Changing the Object

Decorating an Object

In looking over the chapter on the Decorator pattern in our book I’ve felt that maybe I picked too complex a set of examples. In a Decorator example on this blog I attempted to remedy that with a very easy yet somewhat abstract example. However, I’ve decided to try and have a hugely simple example that is both interactive and solves a practical program in games. The knights of yore represent a good metaphor for the Decorator Design Pattern. The Component (knight) is decorated with armor. The same knight may have more than a single suit of armor and yet easily be recognized as the same knight. We could put him in a time machine and trade his steel suit of armor with one decorated with kevlar or some other modern weapon-stopping armor.

In a game context, different characters can be decorated with different weapons, armor and capabilities. If we have to provide our characters with a set of features at the outset, we can get stuck easily if we want to make changes to the character. The Decorator pattern recognizes that in dynamic situations, you need dynamic solutions. You don’t want to have to create a new character every time the character changes. With the Decorator, it’s easy to make changes without changing the core component (character). In this example, I used a graphic warrior and three different graphic semi-opaque graphic armor. To optimize the simplicity, each of the four elements—a component (character) and three types of armor (shield, breast plate and helmet) serve to illustrate the pattern. Further, I used a different class for each as well. These were stored in the library as Sprites. Use the Play and Download buttons below to become familiar with the pattern:
playkilroy

If you click the Play button, the initial figure is the “Concrete Component” participant, and as you click each button in turn, a new “Concrete Decorator” appears. (If you keep clicking the decorator buttons, the decorators accumulate. You can add a line of code to remove them easy enough, but I didn’t in an effort to keep it as simple as pie.)

The Classes

The class diagram and the whole pattern always leaves me with a question mark over my head like a befuddled cartoon character. However, after looking at the class diagram for a while, it begins to make sense. The unusual aspect of the pattern is that the abstract class Decorator subclasses the abstract class Component. In other words, one abstract class inherits from another. Further, the Decorator “wraps” the Component. Figure 1 shows the Decorator class diagram:

<em><strong>Figure 1:</strong> Decorator class diagram</em>

Figure 1: Decorator class diagram

The major feature of the design pattern is the curving reference (an aggregate relationship) from the Decorator to the Component. The inheritance of the ConcreteComponent is a straight inheritance from an abstract class. That’s pretty clear. However, the “wrapping” looks a bit different and one way to “see” it is through the Client. Assuming that the concrete object (the Warrior) is already there, the following code is involved in wrapping the component in a concrete decorator (a Shield, for example.) The code in the Client looks like the following:

?View Code ACTIONSCRIPT
1
2
conComponent = new DecShield(conComponent);
mover.addChild(conComponent.getarmor());

In this example you have the following:

  • conComponent is typed as a Component
  • conComponent instantiates a concrete decorator with itself as a parameter
  • the conComponent instance invokes the getarmor() method, a Component method, that returns the armor’s image

The trick is that each of the concrete decorators inherits both the Component and Decorator interfaces. As a result, the armor (or anything else) is able to change the appearance of the component without changing the concrete component itself.
Read more…

Share

Parallel Tasks: Fork and Join

Parallel Tasks Branch in a Program Sequence

Parallel Tasks Branch in a Program Sequence

A couple of years ago I had a post on the Template Method, and in that post I grumbled about using flow charts in programming. In OOP and Design Pattern programming, the class diagram shows the relationship between objects and more or less leads the programmer to think in terms of objects and relationships. Flow charts encourage sequential thinking and not OOP thinking.

As noted in discussing Parallel Loops, you saw that the pattern applied a single operation to many data elements. With the Parallel Tasks pattern, you add a fork in the flow of control using distinct asynchronous operations that can run simultaneously. An analogous situation would be carpenters who saw and sand wood to prepare it for building a cabinet. The sawing and the sanding are two distinct tasks that can be completed simultaneously and asynchronously. Once both are complete, they can merge back to a single operation of fitting the cabinet together. At first, that sounded like a flow branch, but it’s not necessarily. In fact, it calls for a factory that each can be processed with. So, there’s a lot we can learn from the C#/.NET 4 implementation of parallel programming that we can use with ActionScript 3.0. To get started open up Parallel Programming with Microsoft .NET: Design Patterns for Decomposition and Coordination on Multicore Architectures to Chapter 3 (Parallel Tasks) or just click the //P Book button below:
bookBtn

The Task Factory

Fortunately for us, we have no Task class, System.Threading.Tasks namespace along with the static Task.Factory property with an instance of TaskFactory like C#. I say fortunately because that means we can make our own TaskFactory.

The //P Book provides us with the key ingredients:

  1. Factory Method class
  2. Product class (implied)
  3. Task.Factory property
  4. A forking method (StartNew)
  5. A join method (Wait)

For this post, I want to concentrate only on using the forking and join methods. In a future post, we can look into the more general issue of parallel tasks, but for now I’d like to focus on the operations in ActionScript 3.0 for event dispatching and handling.

Do Fork

In order not to appear too obsessed with avoiding sequential programming, let me note that every method is usually nothing more than a sequence of statements and operations. When discussing the flow of control in a program, we often come to points where one object must be used before another can be used. In dealing with parallel tasks, the same issue comes up. Yes, it’s far more efficient to use separate cores to deal with different tasks concurrently, but that doesn’t mean that the tasks can be used as soon as they are completed. For example, in building a house, you can simultaneously build the foundation, four side and a roof, but they need to follow the sequence:

  1. foundation
  2. walls
  3. roof

What we’re really dealing with is scheduling, and in ActionScirpt 3.0, scheduling can be handled by event dispatching. To get started, this post will handle a call to the event handler in a Join class. Without even working about the foundation and roof, this will begin with setting up the left and right walls. For now, we’ll assume that both walls will be handled, but even though both walls can be handled (built) simultaneously with two different cores, we have to put up the right wall first. As soon as a part is complete, it will dispatch a message to the Join class. This is still unfinished, but it provides a general idea of what we hope to accomplish. Figure 1 provides an overview:

<em><strong>Figure 1: </strong> Overview of Fork and Join</em>

Figure 1: Overview of Fork and Join

At this point, the Client requests a left and right wall from the Fork class. Each is created in a Factory and displayed. The problem is, that they have to be arranged so that the right wall appears first and then the left wall, no matter which order they are actually completed in. As soon as each is completed, it fires off the an event to see the sequence. In the next post, we’ll see about how to go about actually sequencing the parts, but for now, a trace statement will just remind us that the right wall has to be delivered first. You can see the download the files and run the example with the buttons below:
playkilroy

At this point you will see two walls appear simultaneously. The Fork class uses the event dispatched in the Join class to simulate a “Wait” event in sequencing. (Besides the wall, you will also get a trace() message about the sequence; no matter which wall is finished first.) It needs more work, but Parallel Tasks is better handled in small bites. This is the first bite (or byte…).
Read more…

Share
Categories: Parallel Programming