ActionScript 3.0 and Multithreading #2: Green Thread Interleaving

Interleaving Threads are like Alternate Hammer Strikes
With access to a single processor, any green threads need to take into account interleaving. This post provides a demonstration of using interleaving with a Factory Method pattern. Basically, interleaving refers to two threads being processed simultaneously. One part of a thread is processed, and then a part of another thread is processed. The simplest way to do this with ActionScript 3.0 is to use a Timer class. Ideally, the two threads are processed on separate cores of a multi-core processor. (Adobe PhotoShop uses multiple cores through pixel bending; so there’s hope that we might be able to figure out a way to work this example into a way to use multiple processors for multiple threads—true parallel programming.) The Timer object has two parameters, delay and repeat:
Timer(delay, repeat);
Between the repeats and delay, each thread segment takes a “turn.”
Think of it as two men working with sledge hammers taking alternating hammer blows on a railroad spike. When one lifts his hammer, the other is striking downwards, and vice versa.
Usually, demonstrations of this kind of multithreaded process are illustrated with counter loops. However, the point is to show “expensive” processes, and so I decided to make the counters with graphic PNG squares numbered from 0-9. A counter display consists of 4-digits. Each graphic image had to be loaded and displayed as it was called by a timed, interleaved Timer objects. Because of the delay in the Timer object, it was possible to slip in the two “threads” and watch as the two counters simultaneously displayed the numbers. Also, the expensive counter slowed the process enough so that you can see the simultaneous counting “threads.” Click the play button to see the results and the download to see all of the class code:

![]()
My thoughts have been that if we can work out a way to simulate multithreaded programming, we’ll better appreciate what’s going on and start writing code for multi-core processors. Naturally, all of us would rather see ActionScript 3.0 classes where we could create multiple threads with the knowledge that those threads would be sent to separate cores for processing. I have a lot of faith that this will come because of the momentum that concurrent programming has generated.
So What About Design Patterns?
You may be asking yourself,
What can I do with all of those design patterns I learned? How can they be used with multithreaded programming?
Not to worry. Knowing design patterns is helpful in visualizing multiple threads and programming to them. For the example here, I used a Factory Method (again) because it is a clear way to visualize the process of multithreaded programming. Figure 1 illustrates the two threads concurrently but separately instantiating the two product objects. (The abstract classes and factories are assumed—just the threads directly to the products are shown for the purposes of illustration.)

Figure 1: Visualizing multithreaded process in Factory Method Pattern
So the question really is how to set up interleaving to generate multiple threads. I looked at different examples, and most of them showed some kind of timing—either with the Timer class or nested loops. Nested loops give me the creeps;so I decided on using the Client to take care of the interleaving by making alternating timed requests to two different products. The following listing (next page) shows the code for the Client making requests through the Factory Method design pattern:
Read more…
ActionScript 3.0 OOP & Design Patterns Beginner Start
This post is one that I can easily reference for beginners in OOP and Design Patterns when writing the posts for the Beginners Series. For many, including beginners, it may be too basic, but just in case a developer interested in taking the OOP route is unfamiliar with programming ActionScript 3.0 off the Timeline in Flash Professional or away from a Flex Project in Flash Builder, this will be a quick starting point to take the road less traveled in OOP and Design Patterns. (The instructions for getting started with Flash Builder are a bit long. However, you’ll find the instructions for getting started with Flash Pro following them.)
Starting An ActionScript 3.0 Project in Flash Builder
As far as this series is concerned, the focus will be on creating objects and design patterns in ActionScript 3.0 using an ActionScript Project in Flash Builder and adding ActionScript classes and interfaces. At some point, we may introduce some Flex features, but you’re better off getting a good Flex book and working with it.
Step 1: Open an ActionScript Project
Select File > New > ActionScript Project from the menu bar. Figure 1 shows what you will see:

Figure 1: Select ActionScirpt Project in Flash Builder
Step 2: Name Your Project
As soon as you select ActionScript Project, a New ActionScript Project window appears. In the Project name: box type in the name of your project. Figure 2 shows that the name “BeginOOP” is used.

Figure 2: Adding a Project name
Step 3: Click Next (see Figure 2) and add a Client name
When you click the Next button, you’ll see the second step in creating an ActionScript project. Here is where you provide a name for the main class in the project. Since we’ll be working with design patterns, you’ll soon learn that the requesting class is named Client; so you’re likely to see “Client” used as the main project class. (See this Simple Explanation as to why the name Client is preferred.) The default name for the class is the project name; so you’ll have to change it as shown in Figure 3.
Read more…
Beginners OOP & Design Patterns in ActionScript 3.0 Post 2: Code Organizer

A Stack is More than the Sum of its parts
The very first thing to learn about OOP and Design Patterns is that they were not intended to optimize program speed or even efficiency. They were developed to increase programmer efficiency and cut back on wasteful wheel re-invention. They help organize your code so that you can accomplish more and not spend as much time unraveling poorly organized code, work better with teams on large-scale projects and re-use program parts on new programs.
If you’re thinking,
Well that’s a step backwards…
think again. Early coding was done by setting switches, then moved up to microcoding (1′s and 0′s representing switch settings), then to machine language, on to assembly language and finally up to higher level languages like Fortran and eventually to Java and ActionScript 3.0 (with lots of half-steps and side-steps in between.) Each step added more “overhead” to the code which reduced efficiency. If you really want “efficient code” you’d better become acquainted with assembly language. You write programs using opcodes to work directly with the processor and memory. (Who can ever forget that LDA means load the accumulator? Lots of people can forget it!)
Reality Sui Generis
When you think of a key word like trace(), if, for or any number of other ActionScript 3.0 terms, you probably don’t think that those statements are really a combination of other instructions (coded operations). That’s good that you don’t think in terms of 0s and 1s when you’re programming. ActionScript 3.0 words make something happen. If you string them together in programming logic, more stuff happens.
Because you know that the instructions in ActionScript 3.0 are really lower level instructions bound together, if you begin to think of objects in OOP programming in the same way that you do keywords in ActionScript you can begin to see how objects are “things” just as keywords are things. For example, the following script (in the Actions panel in Flash Pro) creates a circle and places it on the screen. You can see that it takes six lines of code to make it work:
1 2 3 4 5 6 | var myOrb:Shape=new Shape(); myOrb.graphics.beginFill(0xcc0000); myOrb.graphics.lineStyle(4, 0x0000cc); myOrb.graphics.drawCircle(200,200,100); myOrb.graphics.endFill(); addChild(myOrb); |

Your Actions panel needs a proper burial, right next to Ralph, your departed pet goldfish
Next, if we take the same code for creating the circle (all 6 lines), we can turn it into a “thing”—an object. However, just like you don’t think of trace() as a bunch of commands you cannot see, the object you’re creating with the 6 lines of code is a reality sui generis—an entity in and of itself. It has characteristics of a “Circle” object just like a “Haystack” object has different characteristics not understood by the individual straws. (Think of “roll in the hay” and a “roll on the straw” and you’ll see what I mean.)
From Lines of Code to Objects
Beginning with the 6 lines of code to create an object, we’ll use the following steps:
- Open a new ActionScript 3.0 Class File
- Add the following code and save the file as Circle.as
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.display.Shape; //The class is the object //By extending another class, it gets all of the properties //and methods of the other object (class). public class Circle extends Sprite { //This is a property of the object //Private properties are encapsulated private var myOrb:Shape=new Shape(); public function Circle() { doCircle(0xcc0000,0x0000cc,200,200,3,100); } //This is a method //Private methods are encapsulated private function doCircle(fc:uint, bc:uint,ex:Number,why:Number,bw:uint,radius:Number) { myOrb.graphics.beginFill(fc); myOrb.graphics.lineStyle(bw, bc); myOrb.graphics.drawCircle(ex,why,radius); myOrb.graphics.endFill(); addChild(myOrb); } } } |
As you can see in the function doCircle() we only used 5 of the original 6 lines. That’s because the first line was declared a private variable and instantiated outside of the function. When a function is part of a class, it is known as a method. The private variable, myOrb, is a property of the class. Both are private meaning that they can only be accessed from within the class. Another way of putting it is that they are encapsulated.
If you think about it as a way of making all of that code a single “thing” in the same way that the trace() statement is a single “thing” the concept of encapsulation makes more sense. Suppose we ran a trace() statement and something unexpected happened. It was affected by some outside influence that somehow had access to the trace() statement. By encapsulating the property and method of the Circle “thing” we just made, we’re not going to get any unexpected behavior.
Let’s say that I want a circle now, all if have to do is to declare an instance of the Circle class. So instead of writing those 6 lines, I’d just write:
var myCircle=new Circle();
That’s it. Presto-chango!, a circle appears on the screen! Now, just like you think of trace() and Shape as “things” in ActionScript 3.0, you can think of Circle as another “thing” you have at your disposal when programming. Likewise, just like Sprite and Shape, Circle has properties and methods.
For You OOP ActionScript 3.0 Beginners who are also Artists…
A while ago, we had some posts for artists who decided to do some coding with ActionScript 3.0. We made a series of three videos on some of the basics of OOP that all OOP beginners might find helpful.
Also, lest you think that we devalue artists on this blog look at our praise of artists (and animators).
Parallel Programming on the Radar for Adobe

Where's the Beef?
Particularly galling was Kevin’s pontification exhorting “academics” to get cracking with parallel programming (citing Paul Steinberg) :
If academia treats parallel programming and data structures like a specialized field of study, walled off into a couple courses and ignored by the general curricula, it will be doing a disservice to its students.
First of all universities do teach parallel programming. A new colleague of mine who just received his computer science Ph.D. from Georgia Tech (a southern version of MIT or India’s IIT) knew all about parallel programming; so, it is something that already is taught in “academia.” (That’s where the concepts were invented.)
Second, if we heeded Kevin’s advice, we’d drop the fledgling ActionScript 3.0 courses you can find here and there in universities and go C# big time. That’s because C# (along with Visual Studio 2010) support parallel programming and other than “my own team’s Pixel Bender in Flash” that Kevin mentions, there’s very little support for parallel programming from Adobe—at least support that’s visible and usable like it is with C# and the .NET framework.
Third, while there’s a brisk discussion at OOPSLA (SPLASH) meetings of parallel programming, there’s no one from Adobe there. (I’ve given several presentations using ActionScript 3.0 in design patterns at these meetings but have never met anyone from Adobe—lots from Microsoft though.) So, while MAX is dandy for the Adobe fanboys, and Intel Developers Forums are great for rallying Intel multicore solutions for hardware, the software giants are at OOPSLA where design patterns were invented. You’ll find (like me) that if you’re the dumbest person at a conference, you can learn a lot.
Let me apologize for this mid-week rant, but like a lot of us who are huge supporters of ActionScript 3.0, it’s very frustrating to see languages like C# and Java (and even Python) support parallel programming and then read a post like Kevin’s telling us to “hop to it” while not having the developer tools to do so. Even worse, if we took Kevin’s advice seriously, we’d probably use C# and C++ on the .NET framework and kiss ActionScript 3.0 goodbye.
ActionScript 3.0 and Multithreading #1: Defining the Problem

Is only one of your processors doing all the work?
What Do the Multicores Do?
I have a few computers, and the ones that I use the most have multi-core Intel Core 2 Duo CPUs (Two Macs and a Win 7 PC.) The Intel Core 2 Duo processor has 2 processors (or cores), but from what I’ve read, one seems to do the work and the other one is mostly unused. If your processor is “quad,” you’ve got 4 processors; but you’re only using one—or more accurately, you might say that you have access to only one for programming. Perhaps the “other” processor may be doing some UI housekeeping or some other chore while the “processing” processor is working on your program, but it could be doing nothing. This would depend on your operating system. However, all I know for certain is that while programming, I can only program to a single processor at a time.
If we have a multi-core processors; why do write single-core programs?
Along with multicore processors is multithreading in programming. In a nutshell, multithreading is running two or more threads at the same time. A thread is a task your computer is processing and multiple threads are tasks that are part of a single process. Imagine several people working on a house at the same time. Some are working on carpentry, some on plumbing and some on masonry. Think of each task as a thread that are part of the same process—building a house. Most of the multithreading that goes on is handled by a single processor that quickly switches between tasks so that it appears that it is processing them simultaneously. If you’ve ever had to wait for a big fat graphic to be rendered, you have an idea of how handy it would be to have more than a single processor working on the graphic at the same time using multiple and parallel threads. Figure 1 illustrates this point:

Figure 1: Parallel processing two threads simultaneously.
Instead of static two-dimentional graphics, imagine three-dimentional animated graphics, and you can get a better idea of why multithreaded programming to multicore processors is important for applications like Flash and Flash Builder.
Before going on, some key concepts need to be quickly clarified:
- Multi-core processor: Two or more processors called “cores” reside in a single component. The cores can execute and read instructions (programs.)
- Multithreaded programming: More than a single thread can be programmed and processed simultaneously. In relation to a multi-core processors, separate cores can be used to process separate threads (tasks in a program.)
- Parallel Programming: Processing multiple threads simultaneously on different hardware resources or processing resources.
- Concurrent Programming: Programming instructions as collections of interacting computational processes. Often used in conjunction with parallel programming when multiple processing resources are available.
- Green Threading: The term “green threads” refers to the process of scheduling threads on virtual machines instead of the underlying operating system. Green threading is simply the process of creating green threads and the virtual machines to process them. (Green threadin’ refers to the same process while listening to boogie music.)
You can get a running start by looking at the first chapter of Multi-Core Programming: Increasing Performance through Software Multithreading by Shameem Akhter and Jason Roberts. ( The entire book is available for about $60.) Another good resource is a talk by GoF co-author Ralph Johnson where you can see the relationship between design patterns and parallel programs. Several ActionScript 3.0 Multi-thread discussions may be helpful. Jesse Warden’s has lots of information about green threading and some design patterns he tried. Speaking of green threads, you can find ActionScript 3.0 examples here at Generalrelativity.
(Continue to see an example using a little Factory Method.) Read more…
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
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:
- You’re using ActionScript 3.0 with either Flash Builder (FB) or Flash Professional (FP).
- You know how to write a program that does something in ActionScript 3.0 beyond snippets on the timeline
- You know what an algorithm is and know how to write at least some in ActionScript 3.0.
- 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:
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.
- Open Flash Builder (FB) and select New -> ActionScript Project from the File menu.
- 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.
- 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.

Figure 1: Adding Project Name

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…
The Vote is In!
Monday 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.
ActionScript 3.0 Saturated Bridge Design Pattern 3: Reuse and Change

Update Bridge and Participants
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.)

Figure 1: Could a Cuckoo Clock be implemented in a Bridge Design Pattern?
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:
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:
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:
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.
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.

ActionScript 3.0 Saturated Bridge Design Pattern 2: Bridge Clock Implementation

Make an Orthogonally Designed Alarm Clock
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.

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:

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:
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…
ActionScript 3.0 Saturated Bridge Design Pattern 1: Intention

Independent Variation by Decoupling Abstractions and Implementations
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:
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:
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:

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…

Bill Sanders
Recent Comments