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

Beginning ActionScript 3.0 Abstraction : The Factory Method at Work

abstractionJoin the Campaign to Stamp Out Ugly!

Gentle Readers: When you click the Play button in this post, the UI that appears isn’t very pretty. That’s because I have no graphic design skills. By changing the requests in the Client class, you could easily make a much nicer UI. Why not give it a shot and send us your revised Client request set? You can even add new Concrete Creators and Products. Send in your refinements to our comment section. Either that or click Play and see Ugly!

The Concreteness of Abstraction

The first time I went to London, I picked up a Tube Map (Map of the London Underground) and was able to get where I wanted to go. The map of London’s tube is a masterpiece of clarity and abstraction. Based on electrical circuitry, it’s very easy to find one’s way around London even on a first visit. Likewise, Paris’ Metro has an almost identical type of map for it’s underground system, and it too is easy to find where you want to go. The secret is having just enough detail to use the system and not so much detail to make its use confusing. Further the coding is clear: different colors depict different named lines. Bakerloo is brown, Circle is yellow, Central is red and District is green. At a glance you see that arriving at Heathrow Airport, you take the Piccadilly line into town (purple) and switch lines wherever you see a white circle off the Piccadilly line. The details are not provided, and the Thames river does not run along the neat geometrical angles shown on the Tube Map. It’s just a reference point and lets you know whether you’re north or south of the Thames. The river’s or tube’s exact shape doesn’t matter; the whole thing is an abstraction of London’s subway system and a major feature of the city. The details would just get in the way of clarity.

Abstraction in OOP and Design Patterns works the same way. An object only exposes as much information as the client (requesting object) requires. The perfect abstract structure in a design pattern is an Interface because it is nothing but abstract methods. The only way to really appreciate abstraction is to see it in action; so this post concentrates on demonstrating abstractions in a fundamental design pattern—the Factory Method.

Two Interfaces and some Concrete Classes

The Factory Method requires a factory interface called Creator and a “product” interface called Product. The Creator interface provides a factory method function to create concrete instances of products through the abstract Product interface. In this implementation of the Factory Method Design Pattern, both abstract participants are interfaces (Creator and Product). Figure 1 shows the relationship between the participants in the design pattern:

<em><strong>Figure 1: </strong> Factory Method Design Pattern</em>

Figure 1: Factory Method Design Pattern

In a step-through of the pattern you see the following:

  1. Client wants a certain product. Makes request through the Creator (factory)
  2. Concrete creator specifies the concrete product and instantiates an instance, returning it to the Client

It’s a very straightforward pattern, but often beginners will puzzle over why all the work simply to get a class instance? The answer to that question lies more in the larger implementations and re-use of the pattern than it does in the small example used here. However, a good general answer is that it loosely binds the product to the request. If you change the product’s contents, you should not have to change anything else in the pattern. The Client makes the request through an abstraction and really doesn’t care about the details of the product. If the product is changed, the exact same request brings up a different object. However, nothing has to be changed to access the new object. Use the buttons below to download and play the example:
kilroyplay

Chapter 2 in our book, and other posts on this blog go into detail about the Factory Method. Here the focus is on abstraction, and the Factory Method is merely used to illustrate the power of abstraction. In order to show the range of products that can be generated from the same abstract interfaces, I used both component UIs and graphic background Shape objects as products.

Using Abstractions and Programming to the Interface

One of the key principles of design pattern programming is,

Program to the Interface and not the implementation….

In order to see both how abstractions are used and how relations work in the n the Factory Method pattern, Figure 2 shows code snippets related to each of the participants (classes and relationships).

<em><strong>Figure 2: </strong> Coded Elements of the Factory Method pattern</em>

Figure 2: Coded Elements of the Factory Method pattern


In looking at Figure 2 code snippets, notice how many times that Creator or Product are used. Both reflect the wholly abstract interfaces in the program. By making references to the interfaces (or abstract classes), the binding between the Client and the requests is very loose. By having loose binding through abstractions, the developer can better update and change the program. The only part of the objects exposed are those that are required. If the concrete products change, the Client is not tightly bound to the concrete elements because the requests hold references to the abstract interfaces and not the concrete participants. (Read on to see how these are all put together!)
Read more…

Share

Parallel Loops: The First Multicore Design Pattern

parallelLoopFree //P Book
In looking at Parallel Loops as a design pattern in Parallel Programming with Microsoft .NET: Design Patterns for Decomposition and Coordination on Multicore Architectures, I found myself asking about the different participants. All that I could find were some relatively simple loops using the C# 4 format for parallel loops. (By the way, the parallel programming book is available free online –click //P Book button– if you’re interested—the upper left-hand corner of the page provides the links to all the chapters. Click on Parallel Loops to see what this post is based on.)
bookBtn

The Pattern that’s Easy to Understand

In thinking about parallel loops, I have no argument with their utility for speeding up application processing. (In this post, we have an ActionScript 3.0 game example.) Further, I found their explanation as to when to use the pattern to be clear:

Use the Parallel Loop pattern when you need to perform the same independent operation for each element of a collection or for a fixed number of iterations. The steps of a loop are independent if they don’t write to memory locations or files that are read by other steps.

You got two (or more) loops that have to be completed at roughly the same time, they’re not connected to each other directly, and so they won’t conflict. Why not run them in parallel? Makes perfect sense to do so. The chapter provides more details as when to use the Parallel Loops pattern, but the general explanation is done nicely.

However, after reading the chapter two thoughts crossed my mind:

  1. Is this really a design pattern?
  2. How would this look in ActionScript 3?

Let’s examine these two issues.

Where’s the Pattern?

In looking at Parallel Loops in C#, the examples show how to use the C#4 statements, Parallel.For and Parallel.ForEach. I wrote programs for each statement, but was at a loss to see where either statement was especially designed to enhance parallel programming as a pattern. Consider the following simple program in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Threading.Tasks;
//Parallel For loop
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 20;
            Parallel.For(0, n, k =>
            {
                Console.WriteLine(k);
            });
        }
    }
}

The results are sent to the screen via the console and can be seen in Figure 1:

<em><strong>Figure 1: </strong> Parallel For loop</em>

Figure 1: Parallel For loop

As you can see, the output is non-sequential, but other than assuming that separate cores were involved in the processing, there’s only one loop processed. (This is an example I cooked up to illustrate how the Parallel.For loop works.) In the Chapter 2 example (which you can see in the online book), it is not clear what’s being processed. It appears as multiple accounts with multiple properties are being processed, but it’s about as clear as mud, and it’s equally unclear where the parallel loops are processed.

I had to ask, Are we really talking about Design Patterns or are these examples simply showing off C# multicore statements? It would be very helpful if their examples were better–you can’t just hand the reader an example and then run one with a sequential statement and the other with the parallel version of the same example, and say, “See! That’s a Parallel Loop!” Sheeeze!

Back to the question of are these really Design Patterns, and after spending a lot of time and head scratching, I believe they are. Essentially, what the chapter on Parallel Loops is doing is showing the //Loop as a general solution where multiple loops can be processed simultaneously. True, these patterns are different than the ones that GoF originally developed, and they are at a much lower level. There are no class diagrams, classes, interfaces or the collection of participants that we generally associate with design patterns. Rather, they are patterns that we can use when we have access to multiple cores. Ironically, while the issue of “What pattern is the most appropriate?” is equivocal to many DP programmers, that question appears to be a bit more self-obvious with the Parallel Loops. You’ve got two (or more) independent loops? Use the Parallel Loops pattern! That’s a lot easier than deciding whether to use a Visitor or Decorator pattern.

Love the Lambda! One of the features that I really like in the parallel for loop is the use of a lambda expression in the loop format. The segment, …Parallel.For(0, n, k =>… formats the loop with the starting value (0), the top value (n) and the increment (k) in a manner that is sweetly clear. If anyone at Adobe is listening, Put Lambda in the next version of ActionScript, please!.

Moving right along…

Parallel Loops in ActionScript 3.0

It took me about two seconds to come up with an example of where parallel loops would be handy in a Flash/Flex application. (It’ll probably take you even less time!) My example is from a combat game where two sides clash. After each fighting event, both sides have to count up their losses (to be subtracted) and resupply (to be added) to all.

?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
package
{
	import flash.display.Sprite;
	import flash.text.TextField;
 
	public class WarriorObjects extends Sprite
	{
		private var teal:Object=new Object();
		private var grape:Object=new Object();
		private var tealField:TextField=new TextField();
		private var grapeField:TextField=new TextField();
		public function WarriorObjects()
		{
			tealField.x=20,tealField.y=20;
			tealField.multiline=true;
			tealField.width=250, tealField.height=100;
			tealField.text="Teal Warrior \n";
			addChild(tealField);
 
			grapeField.x=20,grapeField.y=100;
			grapeField.multiline=true;
			grapeField.width=250, tealField.height=100;
			grapeField.text="Grape Warrior \n";
			addChild(grapeField);
 
			armTeal();
			getTeal();
			armGrape();
			getGrape();
		}
 
		private function armTeal():void
		{
			teal.ammo=10;
			teal.def=20;
			teal.mov=120;
			teal.weapon=30;
		}
 
		private function getTeal():void
		{
			var t:String;
			for(t in teal)
			{
				tealField.appendText("   "+t+": "+String(teal[t])+"\n");
			}
		}
		private function armGrape():void
		{
			grape.ammo=15;
			grape.def=20;
			grape.mov=150;
			grape.weapon=20;
		}
 
		private function getGrape():void
		{
			var g:String;
			for(g in grape)
			{
				grapeField.appendText("   "+g+": "+String(grape[g])+"\n");
			}
		}
	}
}

In this simple illustration, the “Teal” and “Grape” warriors are armed and then using a for..in loop, both sides are evaluated using two functions, getTeal() and getGrape(). Those two loops can be run simultaneously after each clash. The mechanics of working out what values are added to or subtracted from each warrior on each side involves arrays and an algorithm for determining whether points are added to or subtracted from the warriors.

Imagine in a game simulation where all of the warriors on both sides can be quickly prepared for the next round because each can be separately but simultaneously evaluated in parallel loops each using a separate core. The larger and more complex the game, the more valuable this kind of concurrent looping would be.

Feedback Please

You’ve got access to the same book about //P that we do and we’d like to hear from you. Can and should ActionScript adopt some of the C# .NET structures for multicore programming such as Parallel.For and Parallel.ForEach? From the Adobe side, I’ve heard rumors of using Master-Worker models from //P, and that certainly is an interesting approach. What do you think?

Share
Categories: Parallel Programming

Beginner's First Design Pattern: The Template Method

I'm a Design Pattern Virgin too!

It's my first time too!

The Template Method: A Design Pattern with a Principle

In learning OOP and Design Patterns, what you’re learning is a set of principles with associated programming patterns. The Template Method is a valuable starting place because it is used to illustrate the OOP/DP principle called The Hollywood Principle. Be sure to go over the more detailed post on the Hollywood Principle, but for here, you just need to become familiar with the idea that higher level components (like parent classes and interfaces) should call lower level components (like concrete classes), but lower level components, should not call higher level components. The principle is called Hollywood, because the casting director tells the budding actor,

Don’t call us, we’ll call you.

The parent class tells the child class the same thing.

Class Diagram

In order to understand a class diagram, you need to understand class relations. If you understand how to work with an UML, you’re ahead of the game; however, if not, we’re prepared a 4-part series to help you understand the UML and the whole concept of relations between pattern participants. Figure 1 shows the class diagram for the Template Method:

<em><strong>Figure 1: </strong>Template Method

Figure 1: Template Method Class Diagram

After you’ve studied the class diagram for a bit, you can see that it’s made up of one abstract class (all italicized bold lettering indicates an abstract class or interface), and one subclass. One of the operations in the abstract class is concrete (Template Method) and the others are abstract (primitive operations). The abstract methods are italicized.

The template method is made up of the steps in an algorithm, some of which are abstract and some that can be concrete. The template method orders the steps in the algorithm, but the concrete subclass provides concrete implementations of the abstract methods using override. The following two buttons provide a preview of Play and all of the files are available for download:
playkilroy

Abstract Classes and Primitives

One of the more poorly defined concepts in computer programming is that of primitives. Usually when we think of primitives, we think of basic data types like numbers, strings and Booleans. However, the Gang of Four parenthetically note that primitive operations are nothing more than abstract methods. For example, the following is an abstract operation (or method):

?View Code ACTIONSCRIPT
1
2
3
4
5
protected function DoUI():Sprite
{
    throw new IllegalOperationError("Must override");
    return null;
}

Because ActionScript 3.0 has no abstract classes or methods, you have insure that the abstract methods will not be directly instantiated, and one way to do that is to add the illegal operation line. Further to have the proper signature, the method must include some kind of return statement, and a null value does the trick. In the concrete implementation, each primitive operation is overridden and provided concrete operations.

Within the abstract class, you can have both concrete and abstract methods. One of the advantages of an abstract class (compared with an interface) is that abstract classes can have some concrete methods. For example the following template method uses two primitive operations and a concrete one. It’s just is to order the steps of the algorithm, which in this case has three:

?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
...abstract class..
 
public function templateMethod()
{
	DoLogo();
	DoUI();
	DoInfo();
}
 
protected function DoUI():Sprite
{
	throw new IllegalOperationError("Must override");
	return null;
}
 
protected function DoInfo():TextField
{
	throw new IllegalOperationError("Must override");
	return null;
}
 
protected function DoLogo():Sprite
{
	var logo:Sprite=new Sprite();
	return logo;
}
 
...abstract class

So let’s stop a second and consider why and how we’d use a Template Method design based on the following:

  1. An abstract class
  2. A method that orders the steps in an algorithm
  3. At least one abstract method that is overridden by a concrete class that implements the abstract class.

The abstract class affords the programmer flexibility when similar algorithms are used again and again but with slightly different implementations. For example, you may find yourself using a “page algorithm.” The page algorithm loads your logo, creates a UI and then creates content. The logo loading part is going to be the same as you use your logo over and over again. However, the UI and content can vary in several different ways. For that, you need flexibility.

Page Arranger

To get started on the algorithm for a page arranger, we’ll start with the abstract class which is named IServices. One convention you will find in OOP is using an “I” prefacing all Interfaces. I like to do the same thing with abstract classes because other than the concrete properties and methods, you should think of them as a type of interface. (If you’re just getting started in OOP and Design Patterns, you might want to check out Beginners Start to see where the files go in Flash and Flash Builder.)

?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
package
{
	import flash.display.Sprite;
	import flash.errors.IllegalOperationError;
	import flash.net.URLRequest;
	import flash.display.Loader;
 
	//Abstract class. Do not instantiate directly
	//Extend the class for concrete child classes
 
	public class IServices extends Sprite;
	{
 
		private var logoPix:URLRequest=new URLRequest("logo.swf");
		protected var uiPix:URLRequest;
		protected var infoPix:URLRequest;
		private var logoLoader:Loader=new Loader();
		protected var uiLoader:Loader=new Loader();
		protected var infoLoader:Loader=new Loader();
		private var page:Sprite=new Sprite();
		private var logoSprite:Sprite=new Sprite();
		protected var uiSprite:Sprite=new Sprite();
		protected var infoSprite:Sprite=new Sprite();
 
		public function templateMethod():Sprite
		{
			page.addChild(DoLogo());
			page.addChild(DoUI());
			page.addChild(DoInfo());
			return page;
		}
 
		protected function DoUI():Sprite
		{
			throw new IllegalOperationError("Must override");
			return null;
		}
 
		protected function DoInfo():Sprite
		{
			throw new IllegalOperationError("Must override");
			return null;
		}
 
		protected function DoLogo():Sprite
		{
			logoLoader=new Loader();
			logoLoader.x=0;
			logoLoader.y=0;
			logoLoader.load(logoPix);
			logoSprite.addChild(logoLoader);
			return logoSprite;
		}
	}
}

In the abstract class IServices, you can see two abstract methods (primitive operations), and two other methods—DoLogo and templateMethod. The DoLogo is going to be the same assuming that the company keeps the same logo; so you might as well set it up and let the child classes reuse it when they extend the abstract class. However, the UI and information may change, and so both of the methods for what they may include are left up to the concrete implementation.

Next, enter the concrete implementation of the abstract class. In the following you will see that both of the abstract methods are not implemented.

?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
package
{
	import flash.display.Sprite;
	import flash.net.URLRequest;
	import flash.display.Loader;
 
	public class ConcreteService extends IServices
	{
		override protected function DoUI():Sprite
		{
			uiPix=new URLRequest("UI.swf");
			uiLoader=new Loader();
			uiLoader.x=0;
			uiLoader.y=110;
			uiLoader.load(uiPix);
			uiSprite.addChild(uiLoader);
			return uiSprite;
		}
 
		override protected function DoInfo():Sprite
		{
			infoPix=new URLRequest("info.swf");
			infoLoader=new Loader();
			infoLoader.x=150;
			infoLoader.y=110;
			infoLoader.load(infoPix);
			infoSprite.addChild(infoLoader);
			return infoSprite;
		}
	}
}

Keeping in mind that you never implement an abstract class, but you want to program to the abstract class (think interface), you will need a client class to request the use of the concrete implementation. However, by declaring the requesting instantiation through the abstract class, you can keep the binding loose. So the variable tm is typed to IServices but instantiates ConcreteService.

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
package
{
	import flash.display.Sprite;
	public class Client extends Sprite
	{
		private var tm:IServices=new ConcreteService();
		public function Client()
		{
			addChild(tm.templateMethod());
		}
	}
}

As you can see, there’s not much work for the Client. All it has to do is to use addChild to place the returned Sprite object to the display area. The templateMethod() operation is wholly inherited from the IServices class, but at the same time the ConcreteService class allows flexibility of what goes into the DoInfo and DoUI methods.

Play around with this example. The best way is to create some .swf files that you can use instead of the ones provided for download on this post. You’ll begin to see how flexible this design pattern is and how easy it is to use.

Share

ActionScript 3.0 Multi-Core Access Simulator Project

BillzGizmoParallel Loops

The first //P Design Pattern in the Parallel Programming with Microsoft.NET: Design Patterns for Decomposition and Coordination on Multicore Architectures (or //P_DP book) is something they call Parallel Loops. After reading the chapter it was clear that I needed programming access to at least two real cores. In past posts I’ve used interleaving with threads, but for the Parallel Loops pattern, I had to address two separate cores.

Taking inspiration from that famous engineer/artist Rube Goldberg, I devised a two-core access contraption that I could use as a way to either run two independent loops on two different cores or split a larger loopable object (if you haven’t heard of a loopable object; now you have) into two parts for concurrent processing.

Excuse my Single Class

Here are the parts of my multi-core access class:

  1. Flash/Flash Builder working with ActionScript 3.0 (on my client computer)
  2. Flash Media Server access from the same class (on a separate computer) but accessible via ActionScript 3.0 with ActionScript 1.0 on FMS

Doing the same thing with Cold Fusion or PHP would work as well, but using FMS, you can use ActionScript for both cores. Of course, with FMS, all of the ActionScript is AS1 (almost identical to JavaScript); so there’re some differences.

The code for the class is a little hacky, and eventually I want to improve it and make it more interactive as well as provide the user with more options. I built it using Flash Builder. Basically, all the class had to do was to do loops that could be run from one of two cores—local client or FMS server. Also, since some of you might want to fiddle with it, I provided an RTMP address you can use to test it yourself. The following shows the class and 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
package
{
	import flash.display.Sprite;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.text.TextField;
 
	public class ParallelWork extends Sprite
	{
		private var nc:NetConnection;
		private var showCore1:TextField=new TextField();
		private var showCore2:TextField=new TextField();
		private var responder:Responder;
		private var infoCode:String;
		private var rtmpNow:String;
		private var pp:uint;
		public function ParallelWork()
		{
			//rtmpNow="rtmp://192.168.1.43/parallel";
			rtmpNow="rtmp://poobah.mwd.hartford.edu/parallel";
 
			nc=new NetConnection;
			nc.connect (rtmpNow);
			nc.addEventListener (NetStatusEvent.NET_STATUS,confirmConnect);
			addChild(showCore1);
			addChild(showCore2);
		}
 
		private function confirmConnect(e:NetStatusEvent):void
		{
			infoCode=e.info.code;
			if (e.info.code=="NetConnection.Connect.Success")
			{
				showCore1.width=350;
				showCore1.text=infoCode;
				showCore2.width=350;
				showCore2.y=100;
				showCore2.text=infoCode;
				getCore1(1,499000);
				getCore2(500000,1000000);
			}
			else
			{
				showCore1.text=infoCode.substring(22);
			}
		}
 
		private function getCore1(bN:uint,eN:uint):void
		{
			var cB:Number;
			var cE:Number;
			var pN:Number;
 
			for(pp=bN;pp<eN;pp++)
			{
				cB=bN*Math.PI;
				cE=eN*Math.PI;
				pN=pp*Math.PI;
			}
			showCore1.text="Core1: Begin: " + cB + " End: " + cE;
		}
 
		private function getCore2(bN:uint,eN:uint):void
		{
			responder=new Responder(parallelResponse);
			nc.call("parallelOn",responder,bN,eN);
		}
 
		private function parallelResponse(parallelInfo:String):void
		{
			showCore2.text=parallelInfo;
		}
	}
}

You can experiment with the class using the getCore2() method. The first parameter is the starting point of a loop and the second parameter is the ending point. You can set the getCore1() method the same way. The only difference is that getCore1() runs on a local core and getCore2() runs on the remote server’s processor. However, you really do get two different cores.

The server-side (FMS) code is super-simple, and just works out the circumference for a set of values sent from the client side. Unless you have access to FMS or want to download a developer’s version to your local computer, the only thing you can do with it is to test doing loops with multiple cores. The Core 2 processors loops through the beginning and ending values sent to it by the ParallelWork class on the client-side and multiplies each iteration by Math.PI. The way the current example is set up, the code breaks a one million iteration loop into two 500 thousand iteration loops. Each half of the loop is handled independently, as is an important feature of the Parallel Loop design pattern.

In case you want to do some FMS on your own; here’s the FMS (client-side) ActionScript. Keep in mind that it is weakly typed and does not understand data types.

?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
application.onConnect = function(client)
{
 	application.acceptConnection(client);
	trace("parallel connected");
 
	client.parallelOn = function(bN,eN)
	{
 
//This section represents a loop governor placed on my account
//If you have your own or access to a different FMS, you can remove it.
//-------------------------------------------------------
                //Loop governor
	        if(bN>2000000)
	        {
		        bN=2000000;
	        }
	        if(eN>2000000)
	        {
		         eN=2000000;
	         }
//-------------------------------------------------------
		var pp;
		for(pp=bN;pp<eN;pp++)
		{
			var cB;
			var cE;
			var pN;
			cB=bN*Math.PI;
			cE=eN*Math.PI;
			pN=pp * Math.PI;
		}
		 client.parallelInfo="Core2: Begin: "+ cB + " End: " +cE;
		return client.parallelInfo;
	};
}

Click the Play button to give it a whirl and the Download button to retrieve the code:
playkilroy

What you should see is the following:

Core1: Begin: 3.141592653589793 End: 1567654.7341413067
Core2: Begin: 1570796.3267948965 End: 3141592.653589793

You will see Core 1 first, a delay and then Core 2. The delay for Core 2 depends on whether the FMS server has a lot of traffic at the time you give it a run.

Shouldn’t It Be Faster With Two Cores?

If both cores were on the same computer and processing unit, it’d be a lot faster. Further, if one of the cores wasn’t running AS1 on FMS, it’d be faster. However, the purpose of this gizmo is to practice working with dual cores, and the only way (that I know of) to do that right now with ActionScript 3.0 is to use an external accessible program using a different core. I know that Molehill and Pixel Bender have hooks to multiple cores, but I’ll have to keep looking to find those hooks. However, in seeking ways to understand the emerging design patterns for parallel programming with ActionScript 3.0 is to build some kind of testing contraption (objecto) to run ActionScript processes on different cores. This particular one is to test the Parallel Loops design pattern described in //P_DP book. My Neuerfindung is just a modeling and testing tool.

To the end of devising an aggeggio for accessing multiple cores with ActionScript, I welcome any comments for improvements on what I’ve built. If any of you have a program that can do that (not just a link!) please send it in, and if we can use it we will.

In the meantime, take a look at the Parallel Loops pattern, and let’s share ideas about how it can be implemented in ActionScript 3.0. I realize that lots of this is emergent, but the beginning is also the most fun.

Next week, I’d like to really focus on the Parallel Loops pattern and try and provide an example that actually works with ActionScript. And remember, we’re always looking for better ways to accomplish the goal of understanding; so don’t be shy, suggest some ideas—send the working example with the idea, though!

Share
Categories: Parallel Programming