Archive for the 'Flash' Category

ActionScript 3.0 Memento Design Pattern: Flash Media Server 3 Application

Jumping Out of Sequence: Memento Brings You Back

In the last installment on the Memento Design Pattern, you saw an abstract minimalist version to get an idea of how the Memento saved state and got it back again. I used a string variable as the “state” to be saved and retrieved without breaking encapsulation. This time around I used the Memento to solve a more practical and definitely real world problem. How to allow a user to jump around a multimedia online presentation without getting lost. To get an idea of how this works, take a look at a working example of this application at:

http://www.sandlight.com/memento/

When you run the application, you can jump to another level, and then just click the Return to Last button, and it will take you back to your jump point. Also, I put up the zip file to save time in getting all of the code in. Figure 1 shows what you can expect to see:


Figure 1

You can download it at:

Download the FMS Memento Zip File

All of the files are in Flash CS3 format, but the ActionScript files are pretty easy to port over to Flex.

Continue reading ‘ActionScript 3.0 Memento Design Pattern: Flash Media Server 3 Application’

ActionScript 3.0 Memento Design Pattern: Encapsulating Saved States

The Undo Pattern

One of my most-used keyboard combinations is Ctrl+Z to undo just about anything from a program line of code to a graphic drawing. Fortunately for all of us, we can undo just about anything and get back to a state where things were okay—or at least not as bad. The Memento Design Pattern is designed to save state without violating encapsulation. Violating encapsulation could be a problem because encapsulation helps insure the application’s reliability and extensibility. Saving state in itself is pretty simple—just dump the state’s value into a variable, array or object and retrieve it when you need it. However, doing so exposes the state to other objects that might affect it in ways you cannot control.

An Enigma

While the purpose of the Memento is about as clear as you can get, it’s implementation was somewhat of an enigma to me. First, it is one of only three patterns that do not have an interface or abstract class participants (the Singleton and Facade are the others). I suppose that’s not that big of a deal, but those participants in the pattern always seemed to be the glue that holds everything together. That does not mean that the Memento pattern has no interfaces; just not classes identified as such. (More on this further on.) Second, in looking at every Memento design I could find, they seemed to be all over the map—including a couple that added interface participants in the pattern. Like most patterns, I like to begin with a minimalist example to reveal its structure. Also, I like to stick very close to The Gang of Four’s structure; so part of the problem is probably my inherent conservatism when it comes to design patterns. Some of the Memento examples I looked at had me hard-pressed to believe that they were actually Mementos as described by Gamma and his associates. Everyone likes the undo idea, but I’m not so sure that they implement their Mementos with the kind of state encapsulation envisioned by the pattern’s architects.

Sticking Close to the Memento

To get started, take a look at the Memento class diagram. I included labels in red for the nature of the relations between the three main classes and the dog-eared boxes as well:
Memento Class Diagram
Figure 1:Memento Class Diagram

The Gang of Four describes the interfaces in terms of the relations between the three participants as wide and narrow relative to the Memento class. First, the Caretaker class acts like a guardhouse storing the mementos and keeping them from other objects giving it a narrow interface to the Memento class. Second, the Originator has a wide interface so that it can restore itself to a previous state and create mementos that will save a given state.
Continue reading ‘ActionScript 3.0 Memento Design Pattern: Encapsulating Saved States’

ActionScript 3.0 Chain of Responsibility Design Pattern: Decoupling Request and Request Handler

The Chain of Responsibility (CoR) design pattern is used when you need a request handled by the most appropriate object for the request. You don’t need to worry about which object handles the request or even if they’ll handle it the same all the time. For example, suppose you have a constantly changing marketplace and the specs of your request change as well. Rather than building an application that links a specific request to a specific request handler the CoR pattern decouples the two so that when a request is sent, all you know is that the most appropriate object will handle it. Our department buys Flash drives in bulk from China. In the request for the drives I put in a set of criteria and send the request to my Chinese buyer. He is instructed to get the lowest price for the drives as long as they meet the specs in the required bulk. Now I don’t know which manufacturer will win the contract (which object will handle the request), but since I trust my agent in China, I am confident he’ll get the best price even though the price will vary depending on everything from the dollar’s exchange rate with China to the availability of Flash drives. Because so many variables change, I need the flexibility that changes with both the request and the request handler. That’s something like the way the CoR design pattern works—it takes a request and finds the most appropriate way to handle it.

Chain of Responsibility Overview

Because looking at a Class Diagram is useful for seeing the larger context of the design pattern, we’ll look at it first and then go about describing its features.

Figure 1: Chain of Responsibility Class Diagram

This looks fairly simple, and at the basic level it really is. Like some of the other design patterns, the Client is part of the pattern, and so it’s integral. At the center of the pattern is the Handler interface. For the time being, think of the interface as an abstract class because that is what is used in the initial example. The abstract class includes a function for setting successors in a chain and another to handle a request. Finally, the ConcreteHandler classes represent the specific and different classes that handle requests. Generally speaking, an application would include several ConcreteHandler classes, and each is set up in a chain to deal with requests where appropriate.
Continue reading ‘ActionScript 3.0 Chain of Responsibility Design Pattern: Decoupling Request and Request Handler’

Minimalist MVC example using the PureMVC Framework

Several months ago, I was looking for a framework that would streamline AS3 application development. Cairngorm and PureMVC were the most mature frameworks out there and I remember being particularly impressed with PureMVC mainly due to the solid documentation that came with it. Cairngorm may be robust, but I just couldn’t get my head wrapped around it by glancing at the docs and examples. In contrast, PureMVC came with a Conceptual Diagram that explained the framework using the design patterns that I was familiar with. Cairngorm does have similar diagrams that explain its microarchitecture, but it exemplifies my initial thoughts — I just couldn’t get a quick, big picture understanding of it easily. Not only has Cliff Hall done a masterful job on the PureMVC framework, but the effort he’s put into the documentation really underscores the importance of documentation and diagrams on dissemination and adoption.

Cairngorm or PureMVC?
Recently, Ali Mills and Luke Bayes made a presentation on Flex Application Frameworks. Their choices essentially boiled down to Cairngorm and PureMVC and concluded that PureMVC came out on top. However, I highly recommend that developers watch the whole presentation as many enterprise developers in the audience made comments that challenged the easy differentiation of the two frameworks. Having the backing of a stable organization like Adobe, as is the case with Cairngorm, means a lot for enterprise development. Also, this post on Bill Lane’s blog and several comments implying that PureMVC is much harder to learn than Cairngorm got me thinking if a really simple application would help scaffold the transition to PureMVC.

I’ve implemented the minimalist example from the MVC chapter of our book (available as a free download from Adobe Devnet) using the PureMVC framework. Now this is not a full-fledged application, but a very minimal example meant to explain the inner workings of the PureMVC framework. Before diving in, a brief introduction to some of the important aspects of the framework will help. This was the hard stuff that I had to internalize before starting out. These concepts are more eloquently explained in much greater detail by Cliff Hall in the framework documentation.

Continue reading ‘Minimalist MVC example using the PureMVC Framework’

Let’s Get Rid of Conditionals!

No Conditionals Please
At the 2007 OOPSLA Conference in Montreal, a professor from New York City was explaining how he taught his introductory computer science classes. Students would be given a problem and they’d go through a number of steps until the solution failed. He found that most of the failures occurred as students became entangled in ever more elaborate conditional statements.

To resolve this problem, he told them they could not use conditional statements, and the general results were both better solutions and better coding. My first reaction in one of the breakout sessions was “No way!” Back in the day, one of my favorite pastimes was working out sort algorithms, and I find it hard to imagine working out even a simple bubble sort without using conditional statements. Other examples quickly came to mind, and I dug in to defend the use of conditional statements from if to switch (and everything in between).

Then he mentioned three magic words: State Design Pattern. This got my undivided attention because of the work I’d done with them and more generally, State Machines. Each class in a State Design Pattern is made up of a set of functions that launch when a certain state in invoked. No if’s in sight. Triggers launch different states, and the state classes provide the context for the particular state. In other words, the triggers just call the state class desired.

Aside from the State Design Pattern, can a decent program be written without a single conditional statement when more than one condition needs to be considered? I think it can be, and I’m beginning to think that much better programs can be developed if conditionals are kept out. To illustrate a simple decision-making process with no conditional statements, the following program has a decision-making process based on user input.

package 
{
	import flash.display.Sprite;
	import fl.controls.Button;
	import flash.events.MouseEvent;
 
	public class Unconditional extends Sprite
	{
		private var men:String;
		private var women:String;
		private var Button1:Button;
		private var Button2:Button;
 
		public function Unconditional ()
		{
			men="Men";
			women="Women";
 
			Button1=new Button();
			Button1.label=men;
			Button1.x=200, Button1.y=150;
			addChild (Button1);
			Button1.addEventListener (MouseEvent.CLICK,doMen);
 
			Button2=new Button();
			Button2.label=women;
			Button2.x=200, Button2.y=200;
			addChild (Button2);
			Button2.addEventListener (MouseEvent.CLICK,doWomen);
		}
		private function doMen (e:MouseEvent)
		{
			trace ("Whatever is appropriate for men");
		}
		private function doWomen (e:MouseEvent)
		{
			trace ("Whatever is appropriate for women");
		}
	}
}

That was a simple program, and it could have been handled with a single method using a conditional statement.

But It Would Have Been Easier….
In thinking about this, you may be thinking of a long list of cases used in a switch statement or even a simple if...else sequence make a program possible. (I mentioned sort algorithms, and I’m sure you can think of others where you just had to have conditionals.) Often, (in fact usually) it’s easier to use conditional statements than to work out a lot of code that does the same thing. However, no one who took up design patterns was looking for an easier way to create code. In my experience, there’s nothing easy about design pattens except when it comes to the all important task of updating and changing a program. So, because it’s easier probably is not the best argument to preserve conditional statements–at least for readers of this blog.

Why Conditionals?
Rather than ask why not conditionals, I think we need to ask why conditionals? Why indeed? If a programmer wants something to happen given an event, ranging from user input to data from a Web service, the event should trigger the actions directly rather than first filter through a conditional statement. It cuts out a step (the conditional scratching its head) and goes right to the solution. So why even use conditionals? Yes, we’re all used to them, but most of us were used to either sequential or procedural programming before tackling OOP or design patterns. If we can get along without conditionals, and keep a direct link between the state to call an action and the action, it would seem to be a better programming structure. Then, when we want to make changes, the events are not tied into a conditional statement, and we don’t have to untangle the conditional webs we weave.

Comments Please
I’d really like to get some feedback on this idea. If you’re thinking, That’s the stupidest thing I’ve ever head, I’ll save you the trouble–that was my initial thought, and it didn’t really help the discussion. Rather, I’m hoping to find some ideas about this — with or without the State Design Pattern. Mainly, I’m interested in this in the context of design patterns in general; specifically how conditionals or lack of them relate to the different kinds of connections between classes. Do they really get in the way of delegation, composition, aggregation and inheritance? Are they simply a shortcut and add little to good structure? Or not?