Archive

Archive for March, 2011

Beginners OOP & Design Patterns in ActionScript 3.0 Post 1 : Rolls-Royces in the Junk Yard

Beautiful algorithms can be isolated in a trashy structure

Beautiful algorithms can be isolated in a trashy structure

C’est magnifique, mais ce n’est pas la guerre. C’est de la folie: French Marshal Pierre Bosquet’s comment after observing the British charge of the Light Brigade. (Bugs Bunny commented, What a bunch of maroons! regarding the same action.)

Beginning Where You are Now

This is the first in a series of posts that look at working with ActionScript 3.0 using Object Oriented Programming (OOP) methods and Design Patterns for those beginning OOP. I had been programming for a very long time before I got involved with OOP and Design Patterns and then I more or less dove into both at the same time. Here are some assumptions I’m making about those of you who are reading this:

  1. You’re using ActionScript 3.0 with either Flash Builder (FB) or Flash Professional (FP).
  2. You know how to write a program that does something in ActionScript 3.0 beyond snippets on the timeline
  3. You know what an algorithm is and know how to write at least some in ActionScript 3.0.
  4. You’re devilishly handsome or jaw dropping beautiful.

This is not a tutorial about how to use Flash Builder or Flash; so if you’re trying to learn Flash/Flex, this tutorial probably is not too helpful except for writing ActionScript 3.0.

The amount of time you’ve been programming is not that important for getting started with this series. The line of demarcation between OOP and Non-OOP programming is quite clear, and this series is about crossing that line; not how long you’ve been on the Non-OOP side. Throughout this series, you will be linked to other posts from this blog for details on one point or another. This series itself is action-oriented in that we’ll be looking at code that you can enter and use to understand OOP and Design Patterns. A lot of the conceptual discussions will be in the linked posts. Your first link is to this Starter Kit. You’ll find other beginner links in that post along with tools you can put on your desktop to help you when you’re writing code.

The Object in OOP

The terms “object” and “class” are almost interchangeable. Following convention, I’ll be referring to an object as instance of a class. In many respects, crossing the line is simply a matter of using classes. In order to see the line-crossing, let’s begin with an example on the sequential side of the line. The following program exemplifies sequential programming. You’ll need a graphic file, so download the one provided (Inspecting OOP) in the post—you’ll see it further on in this post. In Flash, just select the first keyframe on the timeline, open the Actions Panel and dump in the following script:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
var pic:String="inspect.png";
var loader:Loader=new Loader();
var loadUp:URLRequest=new URLRequest(pic);
loader.x=150, loader.y=50;
loader.load(loadUp);
addChild(loader);

When you test it you should see your graphic appear. If that worked out ok, take the program, and the Actions Panel to the back yard. Dig a hole and bury them. You’ll never being using that kind of programming again.

A Quick and Dirty Run Through Flash Builder

Some of the comments we’ve received have indicated that it would be helpful to take a step-by-step trip through Flash Builder to see how to get the ActionScript 3.0 design patterns created. So you might want skip this section if you’re using Flash Professional or if you’re an old hand developing ActionScript 3.0 using Flash Builder.

  1. Open Flash Builder (FB) and select New -> ActionScript Project from the File menu.
  2. When you open the New ActionScript Project window, you will see the page shown in Figure 1. Name the project Beginners1 (in the Project name window) and then click the Next button.
  3. <em><strong>Figure 1: </strong>Adding Project Name</em>

    Figure 1: Adding Project Name

  4. The next window you see has most of the information filled in for you. However, in the Main application file window change the default name to Client.as as shown in Figure 2. Once you’ve made the name change, click the Finish button.
  5. <em><strong>Figure 2: </strong>Indicating the main application file name</em>

    Figure 2: Indicating the main application file name

Now you should be all set to write your ActionScript 3.0 in Flash Builder. However, you need to place your 250 x 250 file in the bin-debug folder. You can download the one I used sitting on the right side of your screen below. (Or click below for the rest of the post if you cannot see the graphic image.)
Read more…

Share

The Vote is In!

ResultsMonday we’ll start a new series for beginners in OOP and Design Patterns using ActionScript 3.0. The series will include examples from both Flex (Flash Builder) and Flash (Flash Professional.) The vote wasn’t even close, but because we believe that concurrent programming (parallel programming, multi-threaded programming) is so crucial to the future of both ActionScript 3.0 and programming in general, we’ll be issuing posts on those as well. In the same polling, there were requests for combo patterns, frameworks, and even one for MVC, but for the time being, we’ll be developing a series for beginners and I’d like to make a run at creating a virtual machine for doing concurrent programming in ActionScript.

However, since we agreed to let you decide, our next post will be to get those who are beginning, intermediate and advanced programmers through the worm hole and into the land of OOP and Design Patterns.

In the meantime ponder this: C’est magnifique, mais ce n’est pas la guerre. C’est de la folie. That’s how the new series begins.

Share
Categories: ActionScript, Flash, Flex

ActionScript 3.0 Saturated Bridge Design Pattern 3: Reuse and Change

Update Bridge and Participants

Update Bridge and Participants

Double Update

When we think of update and change, typically we think of adding new implementations to existing structures. However, what about tweaking a pattern? If you want to reuse a general pattern (like the Bridge we’ve been discussing), what are the “rules” about changing the pattern?

Generally, the purpose of using design patterns is so that you can make changes without disrupting the current objects. That is, you can add a new object in the form of an implemented interface or abstract class without having to worry about existing objects being disrupted or crashing the system. The bigger the project, the more important this is.

How about making a new pattern based on a few adjustments to one of the pattern participants? If you want to re-use the pattern with just a few changes, and you don’t care about the current participants, you can make small changes with big results.

The Movie Clip and Cuckoo Clock

After implementing the alarm clocks, made up of a bridge aggregated instance consisting of an AlarmClock abstract class and an Alarm interface, I considered adding a cuckoo clock to the mix. Instead of just adding a sound, I wanted to have an animated bird pop out of a door making a cuckoo sound and a swinging pendulum along . Figure 1 shows what I wanted to do with my bridge pattern.(Click the Play button to see the results. If you find it easier to follow along with the code in hand, the download button now provides both Flash and Flex compatible files.)

<em><strong>Figure 1:</strong> Could a Cuckoo Clock be implemented in a Bridge Design Pattern?</em>

Figure 1: Could a Cuckoo Clock be implemented in a Bridge Design Pattern?

playkilroy

What’s Changed?

The cuckoo clock would have to have some kind of mechanism to have an opening door and a bird pop out. Further, when the cuckoo bird jumps out, he’ll need a “cuckoo” sound coordinated with the opening door. To make life easy, I decided to throw a cuckoo sound, bird and sliding doors into a MovieClip object and stack it on top of the clock. I re-used the BellClock implementation’s of IAlarmClock for the hands on an analog clock. However, I needed to address the MovieClip through the IAlarm implementation. To do that, I had to include a MovieClip parameter in the existing Bridge design. So, I changed the IAlarm interface to the following:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
package
{
	import flash.display.MovieClip;
 
	public interface IAlarm
	{
		function alarmPlay(mc:MovieClip);
		function alarmOff(mc:MovieClip);
	}
}

Then in the implementation, I can use the MovieClip with the opening door, cuckoo bird and sound. The implementation looks different from the alarm clock bridge because it does not load an MP3 and it does trigger a play or stop play method in the MovieClip. However, there is no code on the Timeline! It’s all in the implementation of the IAlarm:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package
{
	import flash.display.MovieClip;
 
	public class CuckooAlarm implements IAlarm
	{
		private var goCuckoo:MovieClip;
 
		public function alarmPlay(mc:MovieClip)
		{
			goCuckoo=mc;
			goCuckoo.play();
		}
 
		public function alarmOff(mc:MovieClip)
		{
			goCuckoo=mc;
			goCuckoo.gotoAndStop(1);
		}
	}
}

As you can see, the Bridge pattern is altered very little. The IAlarmClock is the same but the implementation is able to reference the MovieClip through the IAlarm now. The following shows the cuckoo clock’s implementation of IAlarmClock:

?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
package
{
	import flash.display.Sprite;
	import flash.display.MovieClip;
 
	public class CuckooClock extends IAlarmClock
	{
		private var minHand:Sprite=new CuckooMin();
		private var hrHand:Sprite=new CuckooHr();
		private var cFace:MovieClip=new CuckooHouse();
		private var alarmDoor:MovieClip=new CuckooDoors();
		private var clockUp:Sprite=new Sprite();
 
		public override function curTime():Sprite
		{
			alarm=new CuckooAlarm();
			cFace.x=100;
			hrHand.x=208.5,hrHand.y=172;
	        hrHand.rotation=(timeNow.hours+(timeNow.minutes/60))*30;
			minHand.x=208.5,minHand.y=172;
			minHand.rotation=timeNow.minutes*6;
			alarmDoor.x=100,alarmDoor.y=1;
			alarmDoor.stop();
			clockUp.addChild(cFace);
			clockUp.addChild(alarmDoor);
			clockUp.addChild(hrHand);
			clockUp.addChild(minHand);
			return clockUp;
		}
 
		public override function doAlarm():void
		{
			alarm.alarmPlay(alarmDoor);
		}
 
		public override function offAlarm():void
		{
			alarm.alarmOff(alarmDoor);
		}
	}
}

The clock is constructed very much like the analog clock in the original Bridge example. The only big difference is the addition of the MovieClip instance (alarmDoor). In communicating with the IAlarm (agregatee) the Bridge serves as a … well bridge… for the implemented IAlarmclock (CuckooClock) to pass the message that it wants the cuckoo to chirp or shut up.

Same Old Client

With the simple changes made, the client doesn’t realize or have to realize that anything is really changed. It makes the same kinds of requests as the original clock-building Bridge does.

?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
package
{
	import flash.display.Sprite;
	import fl.controls.Button;
	import flash.events.MouseEvent;
 
	public class ClientCuckoo extends Sprite
	{
		private var aClock:IAlarmClock;
		private var selectCuckoo:Button=new Button();
		private var playCuckoo:Button=new Button();
		private var quietCuckoo:Button=new Button();
		private var clockNow:Sprite=new Sprite();
 
		public function ClientCuckoo()
		{
			addChild(clockNow);
 
			selectCuckoo.label="Cuckoo Clock";
			selectCuckoo.x=10,selectCuckoo.y=310;
			selectCuckoo.addEventListener(MouseEvent.CLICK,getCuckoo);
			addChild(selectCuckoo);
 
			playCuckoo.label="Play Cuckoo";
			playCuckoo.x=10,playCuckoo.y=340;
			playCuckoo.addEventListener(MouseEvent.CLICK,releaseCuckoo);
			addChild(playCuckoo);
 
			quietCuckoo.label="Quiet Cuckoo!";
			quietCuckoo.x=10,quietCuckoo.y=370;
			quietCuckoo.addEventListener(MouseEvent.CLICK,cageCuckoo);
			addChild(quietCuckoo);
		}
 
		private function getClock()
		{
			removeChild(clockNow);
			clockNow=aClock.curTime();
			clockNow.x=20,clockNow.y=10;
			addChild(clockNow);
		}
 
		private function getCuckoo(e:MouseEvent)
		{
			if (aClock)
			{
				aClock.offAlarm();
			}
			aClock=new CuckooClock();
			getClock();
		}
 
		private function releaseCuckoo(e:MouseEvent)
		{
			if (aClock)
			{
				aClock.doAlarm();
			}
		}
 
		private function cageCuckoo(e:MouseEvent)
		{
			if (aClock)
			{
				aClock.offAlarm();
			}
		}
	}
}

Despite the fact that I changed the method names in the client, any programmer can see that they’re the same ones used for the original alarm clock. (The changes were to bring attention to the new type of clock.)

Easy Changes

Usually when we think of changes and re-use with design patterns, the focus is on different implementations of existing abstract participants. However, design patterns can be envisioned in terms of small changes in the pattern to produce a new implementation of a pattern with minimal changes but opening up the door for a whole new kind of structure and opportunities for that structure. The Bridge pattern offers the flexibility that all design patterns have in terms of making changes without disruptions in the project. At the same time, new structures are just as easy to change for a new set of possible implementations.

The variation in the Bridge pattern is the implementation of an object. With the two alarm clocks we saw that both different implementations of the clock (analog and digital) and the alarms (bell and music).

This wraps up the saturated Bridge series, and I hope you have enough depts in the design of the pattern to use it when you need an appropriate Behavioral design. In this last installment, the purpose has been to keep in mind that changes are easy when your code is in a design pattern, but you can also make little changes in a pattern to open up a whole new set of possibilities. Remember, all kinds of changes are easy with ActionScript 3.0 using design patterns.
query

Share
Categories: Bridge, Saturated Bridge

ActionScript 3.0 Saturated Bridge Design Pattern 2: Bridge Clock Implementation

Independent Variationby Decoupling Abstractions and Implementations

Make an Orthogonally Designed Alarm Clock

Aggregation Magic

In discussing aggregation, the Gang of Four left a lot of loose ends, and the relationship can be difficult to grasp. It’s something like an acquaintance but is stronger. Nevertheless, acquaintances can be just as strong but not be aggregations. So is it really that important to distinguish between aggregation and acquaintances? In most cases the distinction is important because while many similarities exist between them (just as with men and women), the differences change the character of the relationship. Gamma et al point out,

Aggregation implies that an aggregate object and its owner have identical lifetimes, (p. 22)

but that description brings up other questions. We can assume that an aggregate object is the combination of two objects bound through aggregation. However, what is its owner? In Part I of this series, you saw that the Bridge pattern is made up in part of an orthogonal component bound by aggregation. That’s pretty clear, but how is that component owned? Does that mean the parts that make up the component are the owners? If one or the other of the aggregated objects (classes) ceases to be; so will the other one. Thus, the parts are the owners. However, another way of looking at ownership in an aggregate relationship is by examining it parts.

The aggregation relationship is characterized by the Aggregator and Aggregatee as shown in Figure 1.

<em><strong>Figure 1: </strong>Aggregator and Aggregatee</em>

Figure 1: Does the Aggregator own Aggregatee?

In this model, it would appear that the aggregator is the “owner.” It defines the relationship by holding a reference to the aggregatee.

The Orthogonal Bridge

The “aggregateinstance” in Figure 1 is the “bridge” in the Bridge pattern, and it is the orthogonal component discussed in detail in Part I of this series. The next step in understanding the Bridge design pattern is to implement it. The alarm clock provides a clear way to see the relationship between objects linked by an aggregation that makes up an orthogonal component. Figure 2 show the files for the implementation arranged in a File Diagram:

<em><strong>Figure 2: </strong>Bridge File Class Diagram</em>

Figure 2: Bridge File Class Diagram


This Bridge example is quite simple and easy to understand as a Bridge pattern. The two interfaces are made up of an abstract class (IAlarmClock) and an interface (IAlarm.) You can think of the physical alarm clock as an instrument that keeps time and the alarm as a sound it makes to generate an alert. The clock and its alarm can vary independently but work in conjunction. The clock has a time-keeping function that can be used to call the alarm when needed. In the example, the clock implementation is that of an analog clock that rings a bell and a clock radio that plays Ride of the Valkyrires (Wagner’s Walkürenritt). It’s easy to add a different clock implementation (a Cuckoo clock, for example) or a different alarm—a rocket ship blasting off if you wish. The following two buttons will download and Play the example for you:
playkilroy

The clocks do not update, but they should display your accurate local time. You can easily put a Timer object in the program to make the clocks work like running clocks. Likewise, while I did not place an alarm setting function in the clocks, I placed an alarm testing button. That’s so you wouldn’t have to sit around waiting for the alarm to ring. However, it wouldn’t be difficult to do so. In fact if any of you want to place a running clock in the pattern by extending another implementation from the IAlarmClock abstract class, I’d very much like to see it, and I’ll display it on the next blog entry in this series—same with implementations to the IAlarm interface. Okay so where do we start with implementing this pattern? Read on.
Read more…

Share

ActionScript 3.0 Saturated Bridge Design Pattern 1: Intention

Independent Variationby Decoupling Abstractions and Implementations

Independent Variation by Decoupling Abstractions and Implementations

Independent Implementation?

The concept that you can decouple an abstraction from its implementation sounds flat out bizarre. Whether talking about an interface or an abstract class, how in the world is it possible to implement a concrete class that is not affected by changes in the interface? If the abstraction varies, the concrete implementation is either going to change or crash. If you use an interface, you’ll have some kind of abstract method set up that is implemented by a class using the interface and its signature. If I change the interface even minutely, something is going to change in the implementation or it will crash. Suppose I change the return type in one of the methods from a Number to a String, what’s going to happen when I run the program? It will throw an error.

For example, try the following:

?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
//Client
package
{
	import flash.display.Sprite;
 
	public class Client extends Sprite
	{
		private var doFirst:IFace;
		public function Client()
		{
			doFirst=new Imp1();
			trace(doFirst.doThing());
		}
	}
}
 
//Interface
package
{
	public interface IFace
	{
		function doThing():Number;
	}
}
 
//First (correct) Implementation
package
{
	public class Imp1 implements IFace
	{
		public function doThing():Number
		{
			return 55;
		}
	}
}

That works just as expected. No big deal, the interface implementation is correctly formed. Now, make the following variation and try it:

?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
//Modified Client to call new implementation
package
{
	import flash.display.Sprite;
 
	public class Client extends Sprite
	{
		private var doFirst:IFace;
		public function Client()
		{
			doFirst=new Imp2();
			trace(doFirst.doThing());
		}
	}
}
 
//Modified implementation
package
{
	public class Imp2 implements IFace
	{
		public function doThing():String
		{
			return "Hello World!";
		}
	}
}

The only thing that was changed was the return data type from Number to String. Here’s the Crash results:

Line 3 1144: Interface method doThing in namespace IFace is implemented with an incompatible signature in class Imp2.

So how can you have independent variation between an abstraction and its implementation?

The Bridge to the Moon

When thinking about an image for this series on the Bridge design pattern, I considered a number of bridge images. However, the Bridge intention is to,

Decouple an abstraction from its implementation so that the two can vary independently.

The idea of a bridge to the moon popped up because the earth and the moon have different orbits (and a few other things) but share much in common and exert an influence on one another. The idea of a bridge to the moon is one way to think about decoupling and connections at the same time. An even better way is to take a look at the Bridge class diagram in Figure 1:

<em><strong>Figure 1:</strong> Bridge Class Diagram</em>

Figure 1: Bridge Class Diagram

Now, when we think about decoupling an abstraction from its implementation we can see that the Gang of Four made both the abstraction and implementation abstract! The implementation in the sense that we use extend from an abstract class or implements from an interface has a whole new meaning.

When an aggregate relationship exists between two classes (or interfaces) they create something akin to a concurrent object with different implementations possible. In this case the aggregate relationship is between two interfaces (or abstract classes), and you can begin to understand independent variation. So we need to look more closely at what exactly varies.
Read more…

Share