Archive

Archive for the ‘Design Patterns’ Category

Video Game State Machine:No Conditionals Part III

State Video Game!

State Video Game!

State Design Pattern Game

Is the State Pattern the way to go with a game based on videos? First, we have to ask, what varies? In this case, different places on the grid represent different situations in a game environment and depicted in a video. (Actually, any environment that requires unique states presented in videos–such as a guided tour of a museum–would be ). Simply put, the videos vary and each represents a different state. So the answer to the first question is, yes, the State pattern is appropriate.

Second, we must ask, are updates and changes easy with this application of the pattern? In this particular case, I tested several different videos with this applications, and it’s very easy to swap and change videos. In fact, if I want to use .SWF files for animation instead of videos, that too would be a cinch.

Third, we need to consider the code generated. Will using the State pattern generate more code and more work than other patterns or coding strategies? This may be the Achilles’ heel of the pattern used as a game generation design. Consider the following:

  1. Each grid cell is a state
  2. A 19 x 19 grid generates 361 cells
  3. Each cell needs a State class
  4. The grid requires 361 State classes
  5. The Context class requires getter methods for each class
  6. The Context class generates at least 1,444 lines of code (assuming each method takes up 4 lines)
  7. The Context class constructor function requires an additional 361 statements to instantiate instances of each state

If that looks like a lot of code and classes, it is. However, design patterns were originally created to ease the task of very large programs, and just about any way you work it out, 361 different states (video shots) is going to be difficult to keep track of. The biggest problem I can see in this design is in the Context class. The Context keeps track of what state the user is currently in. When states change (and you’ve got 361 of them), you have to include a method in the Context for changing states. There’s where you end up with a very big class. Before going on, though try playing the game and download the files using the buttons below: (By the way, this time there’s a surprise…see if you can find it in the play..be careful, it’ll eat you.)
playkilroy

*Reminder: I’m putting all of the downloads into a general download site stored under “ActionScript 3.0″; so, just click on the latest download and you’ll get all of the files, including the videos and even the Excel spreadsheet with the direction grid.

Read more…

Share
Categories: State

Video Game State Machine:No Conditionals Part II.5

A Better State is at Hand

A Better State is at Hand

A Dot Release

In our previous post on the State Design Pattern, I wanted to have a nice clear example, but in the process, too many parts were left out, and in some respects it was more complicated with the use of the helper class (Distributor) than it had to be. As a result, the design generated multiple instances of the Distributor class and each instance was difficult to control—not to mention the fact that each new instance overloaded the program with unneeded instances. As a result, I decided to simplify the video process by creating a single instance of the Distributor in the Client and just pass the name of the requested video to be played through the same instance using the Distributor’s methods. So instead of having each state return a Sprite instance, they now return a String instance used by the single Distributor instantiated in the Client. The following buttons provide the new files to download and running example:
playkilroy

*Note about Downloads: I’m in the process of moving all of the downloads to the MWDD site at the University of Hartford. It’s still being set up, and I’m working on a way to provide more information about each of the downloads. All of the downloads for this blog will be under ActionScript 3.0/Flash (which includes Flash Builder/Flex).

Secondly, the first example just included two states—one for starting and one for going one step to the east. That helped keep things simple, but it didn’t do much for seeing how the State design pattern can handle the North-East-West-South (NEWS) directions. Figure 1 provides a statechart that shows an NEWS state machine with an additional state to the east. It provides a better idea of where the State pattern can take us.

<em><strong>Figure 1: </strong> Statechart of Direction Relative States</em>

Figure 1: Statechart of Direction Relative States

The statechart shows movement between states and the kinds of transitions relative to a starting position.
Read more…

Share
Categories: State

Video Game State Machine:No Conditionals Part II

Starting State Design Patterns

Starting State Design Patterns

Help for OOP/DP Beginners: Rewind the State Pattern

I started working on the State design pattern, and I realized how easy it is to quickly get lost. The idea of a state machine is pretty clear and simple, and so is the State Design Pattern. However, I find that if I’m away from it for any length of time, it gets all tangled up again—like fishing line in a well-used tackle box. So, in this inserted post between Part I and Part III of the Video Game Machine series of posts, this one is for beginners in the State design pattern.

The two examples used are simple, but both have to get through the tangle of the requests from the Client through the Context requests and on to the concrete states via the State interface. The first example is wholly abstract but really simple. Play and download buttons provide access to get started:
kilroyplay

Overview

Figure 1 shows the State class diagram and the ActionScript 3.0 files so that you can easily see the implementation of the pattern. The Client makes a request for a given state through the Context. The Context checks the current state (think lights on; lights off as two distinctive states) and then requests the action from the current state. So, if current state is lights on and the request is to turn on the lights, it wouldn’t do anything because the state already exists.

<em><strong>Figure 1: </strong> Class and File Diagrams of State Design Pattern</em>

Figure 1: Class and File Diagrams of State Design Pattern

Rather than turning the lights on or off, this example starts with a “Starting” state and a state known as “East1.” So the user is either in the Start State or the East1 State. These two states will be abstract with trace() statements in this first example that helps to see what’s going on, but in the second app in this post, we’ll use videos. Once the State design pattern is established, it’s very easy to add and change objects without crashing the application. That’s what makes the State pattern so valuable; a little extra work at the outset pays huge dividends in the long run.

The Participants

The State design pattern deals with variation in an object’s state. An adventure game can be treated as a series of states that the player enters and leaves. Depending on the state (situation) different things are possible. The state can change from the home base, to the wizard’s fortress to the jungle to an underground cavern maze, into and out of a worm hole, a parallel universe or anything the developer’s mind conjures.

The most important work in the State pattern is Context class. It keeps track of the current state to determine how to handle a request. Imagine three states known as:

  • State 1
  • State 2
  • State 3

State 1 can only remain in its current state or go to State 2. It cannot go directly to State 3. So if the Client requests State 3, the Context realizes that the current state is State 1 and so makes the call to State 1 where the options available in that state do not include a move to State 2.

The determinations are not made using conditional statements. Rather, as each state is called, it reports to the Context establishing itself as the current state. As a State pattern application grows in size, it must generate a separate concrete state for each new situation and possible changes in state. The State interface requires a new method for accessing the new states, and the concrete states must include that method in their structure—even if the method results as a null one. For example, in the State 1 concrete state class, the method to go to State 3 does nothing.
Read more…

Share
Categories: State

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

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

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 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