Archive

Archive for the ‘Design Patterns’ Category

How to Pick the Right Design Pattern: Fortune Favors the Prepared Mind

Deciding on a Design Pattern

Deciding on a Design Pattern

Which Design Pattern Should I Use?
One of the most difficult questions to answer is also the most often asked: How do you know what design pattern to use? My standard response to that query is,
Ask, “What varies?”

Of course, it seems that everything varies just when you need a nice clear answer to that question. The Gang of Four provides a list of design patterns and what varies in each pattern—such as states of an object, an algorithm, responsibilities of an object without subclassing and so on. However, determining the nature of the variation can be as difficult as deciding the design pattern to use as looking at class diagrams. (Download the AIR version of the Variation Table—also known as The Magic Table.)

Go To The Original Source

Chapter 1 in the Gang of Four’s book is the gateway to design pattern knowledge. I must have re-read it 50 times. Further, every time I re-read it, I get something new. You can download Chapter 1 of Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—just click the download button to bring up the PDF file and then save it:
kilroy

Find the section, How to Select a Design Pattern and read it. Even if you don’t get it all the first time through, you’ll have a better idea of design pattern selection. Now you’re all set to continue with the rest of this post. Read on!
Read more…

Share
Categories: Design Patterns

The ActionScript 3.0 Design Pattern Thrill Ride: Part II—Catalyst

Thrill I’ve been working on a project with Adobe Catalyst, and if I didn’t do something for a Design Pattern tour now, it would be put off until I don’t know when. So I put together a non-design pattern application incorporating video and code snippets from the Aid Game. I simply have not had time (given the work I’m doing with Catalyst) to put together a more generic design pattern “thrill ride” that I planned; so while I’m working with Catalyst, I thought I’d might as well do something with design patterns and came up with this more mild tour instead of my planned thrill ride. Figure 1 shows what it looks like:

<em><strong>Figure 1: </strong>Tour through State Design Pattern</em>

Figure 1: Tour through State Design Pattern

As you can see it’s pretty simple—sort of a PowerPoint chat. (Nowhere near as flexible as the one created with the Memento pattern.) So, if you’re interested in a mild tour, click the Play button and hop on:
play

By the way, the Catalyst project has made me far more aware of Flash Builder/Flex code. It uses Flex in its engine. If you’re interested in Catalyst, you can download the Beta at Adobe Labs. I tried importing programs (SWF files) made with design patterns, and it works great. About the only thing I didn’t do with this tour is to put the videos on Flash Media Server—sorry. I was in a hurry and wasn’t sure how to link up FMS to Catalyst. I could have written the code in Flash/Flex and created an SWF file to import into Catalyst, and that works fine, but I’m pretty pressed for time on this project.

As always, your comments and valuable feedback is encouraged. I’ll be back working on this blog as soon as I’m finished with the Catalyst project. Besides, Chandima has been writing knock-out posts to keep you interested!

Share

Separated Presentation: The Classic Model-View-Controller Pattern

This is not an introduction to the MVC pattern, but a look into its implementation in Smalltalk-80 to understand the original intent and function of the Model, View, and Controller triad. Starting with the “classic” MVC helped me understand the evolution of the presentation patterns that came after it. We will look at how a simple MVC app works in Smalltalk-80 and examine how it can be implemented in ActionScript. I am not a Smalltalk programmer and my first task was to find some good resources.

Trygve Reenskaug is credited with the first MVC formulation in Smalltalk in the late 70′s. However, the MVC metaphor was burned into Smalltalk and matured after Reenskaug left Xerox Parc. I found two useful resources on MVC in Smalltalk-80. The first is  A cookbook for using the model-view controller user interface paradigm in Smalltalk-80 by Glenn Krasner and Stephen Pope. The second resource is Applications Programming in Smalltalk-80: How to use Model-View-Controller (MVC) by Steve Burbeck.

Although comprehensive, Krasner and Pope’s article is very readable from an ActionScript perspective. I could just about follow the Smalltalk code listings, identify the early OOP features and appreciate the ancestors of contemporary UI components.  What stood out was how little things have changed in the last 20 to 30 years in OOP and GUI programming. I think the more appropriate observation is how advanced Smalltalk was for its time. Krasner and Pope’s essay is the primary resource for this post.

Model-View-Controller Implementation in Smalltalk-80

The MVC pattern facilitates the separation of concerns when developing interactive graphical applications. The logic and state of the application, how users interact with the application, and how application state is presented to the user are handled by separate elements of the MVC triad. Smalltalk-80 uses the MVC metaphor to provide built-in support for interactive application development. The idea was to provide a set of built-in user interface widgets such as buttons, menus and lists that can be plugged into a GUI application. To use these built-in UI widgets effectively, the application had to be built in accordance with the MVC metaphor. Let’s take a look at the conceptual diagram of a Smalltalk-80 MVC app.

Model-View-Controller (from Krasner & Pope)

Conceptual diagram of MVC in Smalltalk-80 (from Krasner & Pope)

All objects in Smalltalk communicate with each other via messages. Think of messages as a way to invoke methods in an object.

At first glance, the MVC conceptual diagram seemed a little strange. The multitude of arrows indicated more acquaintances than I’m used to seeing in an MVC diagram. Model-View and Controller-Model dependencies ran both ways. The second interesting aspect was that user input goes directly to the Controller. This is a significant change as we generally expect users to interact with UI widgets in the View. In Smalltalk-80, it looks like the raw keyboard and mouse input is fed directly to the Controller. Let’s take a quick look at how the MVC metaphor is supported in Smalltalk-80. Read more…

Share

New Aid Game: The Machine Moves!

February 2, 2010 37 comments

Helper Class is Helped

Helper Class is Helped

I wanted to move on from the original Aid Game, at least as far as the movement was concerned; so I fully fixed it up. With the new set of rules from the previous post of repairing the movement, I realized that if I didn’t generate fully operating movement states, we’d end up overly focusing on the wrong things. So, I set up a class (TimeMachine) to encapsulate the Timer object, and then the Mover class became the child of the TimeMachine using the different TimeMachine Timer properties. Because I instantiated a Timer object in each of the properties in the TimeMachine, I do not believe it is properly an Abstract class. However, like an Abstract class, it is not invoked directly, but rather through inheritance.

Playing the Game by the Rules: First Break the Rules

The nice thing about a State design pattern is that once the rules are established, you can build your algorithms and the different states invoke them according to the rules you’ve established. You can have a number of different algorithms within the State framework, and they should all work in accordance with the rules—no matter what the rules are or what algorithms you use to invoke them.

To see if the revised game follows the movement rules, try and break the rules. The main rule that you can attempt to break is the No reverse without stopping rule. So if you’re going right and you press the Left button, your helicopter should first stop and then you’d have to press the Left button a second time. Or you can reverse direction by pressing the Stop button and then press the opposite direction. Click the Play button to give it a whirl:

play

So go ahead and try to break the rules! If you can; then the design fails. If not, it succeeds. Once you’re finishing playing, download the latest code and see how the rules were applied.

kilroy
Read more…

Share
Categories: State

Fixing the State Machine: Aid Game Repair

January 30, 2010 6 comments

Fixing a State Design

Fixing a State Design Pattern

Getting the States Straight

In a recent post to illustrate the use of composition and delegation, I created a simple game using a State design Pattern—the Aid Game. A lot of people had lots of questions and suggestions for making it better and being one who thrives on improvement and change, I promised to have a post where we’d review it as a State design pattern and not a quick and dirty example of composition.

In this post I’d like to go over some key elements of a State design and to see if we can improve on the original Aid Game by better design of state classes. Also, I’m going to leave the final repairs up to you—I’ll provide some guidelines for improved states, and you can implement them. Also, I’ll provide a little helper class that is an example of continuous movement based on one from our book that Chandima used to illustrate MVC. (I simplified it from the original; so if you look at the MVC chapter—Chapter 12—, you’ll only see pieces of it.)

Why a State Design and What are the States?

To get started, we have to ask the same key question that we should ask for every design we do. Namely,

What varies?

In moving the helicopter around in the Aid Game, the main thing that varies is the state of flight. (Each of the different directions and a stopped state represents a variation in state.) Ergo, I selected the State Design Pattern.

In our simple State design, I used five different states:

  1. Stop
  2. Move Right
  3. Move Left
  4. Move Up
  5. Move Down

Next, I’ll add some rules that were not in the first version:

  • Before reversing direction, you must first go to the Stop state.
  • If a current state is called, it cannot invoke itself.
  • Movement is continuous

Read more…

Share
Categories: State

ActionScript 3.0 State Design Pattern: An Aid Game

January 18, 2010 44 comments

Take This One to Work

Take This One to Work

After creating the post on the acquaintance relationship between classes, I started thinking about the aggregate relationship and delegation. One of the best examples of delegation can be found in the State design patterns. All of the states are delegated to objects that handle each state. So I thought it’d be a good idea to create a little game that demonstrates both delegation and a state engine at work. Then, when I do the post on aggregation relations, I’ll have a simple reference point. This one is set up so that you can put it into your lunch bucket and take it to work. What’s more, it’s designed so that you can extend it into a more interesting game.

I decided that a good starting point would be to have a helicopter fly aid packages to different places on the screen. It would start at the airport and then fly the aid to different sprite objects representing groups of people in need. However, to get started, all I did was to set up five buttons to move the helicopter around the screen beginning at the airport. Figure 1 shows what the game looks like. (It is set up on an 800 by 600 display; so I had to cut off part of the right side to fit in this blog format.) The movement buttons are in the lower left portion of the screen.

<em><strong>Figure 2: </strong> State Pattern moves Helicopter Object</em>

Figure 1: State Pattern moves Helicopter Object

Click on the Play button to get an idea of how it works:
play

Read more…

Share
Categories: State

ActionScript 3.0 Design Patterns New Years Resolution

First off, Happy New Year and Happy New Decade to one and all. By the end of 2010, I hope I’m a better programmer than in 2009.

In order to be a better programmer I need to have a good resolution. I’d like to do something better this year while not abandoning good habits I’ve picked up over the time I’ve been trying to be a better programmer. (That actually makes sense even though a bit convoluted.)

So, now I’ve got to come up with a resolution. The one I want will do the following:

  • It has to be one I can keep. If I aim too high, I may miss the mark and feel I’ve failed to keep a resolution. Aiming too low is just a waste of time.
  • It has to be forgiving. That means that if I don’t keep it 100% of the time, it’s ok. Improvement, not perfection, is the goal. Improving habits eventually become part of my programming DNA, and it’s a step in the ongoing trek to be a better programmer than I was at this time last year.

So my New Year’s resolution is:

Improve nailing down relationships between classes in design patterns.

For example, when I look at a design pattern with an aggregate relationship, I want to be able to immediately imagine what the code looks like for that kind of relationship and how it differs from an acquaintance or some other relationship. Eventually, this will enable me to look at a design pattern in a UML and see the code-class relationships and how it might or might not solve a programming problem.

I’ve probably got a dozen other resolutions for becoming a better programmer, but they’re sort of always there nagging and whittling, nudging me in the right direction. (My wife has thousands of resolutions for me; none having a thing to do with programming!)

Ok, that’s it for me. How about you? What’s your New Year’s programming resolution? Put ‘em in our Comments, and at the end of the year we’ll see how we’ve done.

Share
Categories: Design Patterns

ActionScript 3.0 Design Pattern Re-use and Modification

December 23, 2009 1 comment

Take This One to Work

Take This One to Work

Every Monday I have to separate out the paper, glass, aluminum, and plastic to recycle and take them up to the curb. This last Monday while engaged in this weekly ritual, I thought that recycling a design pattern might be an interesting exercise. Additionally, it’s the kind of design pattern advantage that can be used at work to save re-inventing the wheel when you have a similar development task. You may remember the Dragon Factory where we employed a Factory Method to set up an easy-to-use drag application. In the original Dragon Factory, both the Creator and Product participants had subclasses. However, with only a slight revision, it’s possible to create a little game for making different faces subclassing only the Product interface (abstract class). Figure 1 shows the File-Class Diagram:

<em><strong>Figure 1:</strong> Factory Method with Single Concrete Creator</em>

Figure 1: Factory Method with Single Concrete Creator

You can see the design similarities between this application (MrFace) and the Dragon application. The main difference is that this one has a single concrete factory (FaceCreator) for all of the concrete products. The factory churns out all of the Product children and puts them into an array. The Client requests the array from the Creator and pulls out the elements with a loop. As you can see, they’re all draggable elements. Try out the embedded SWF file below to see how it works:

[swfobj src="http://www.as3dp.com/wp-content/uploads/2009/12/Client1.swf" alt="MrFace" align="none"]

The same Product (from the Dragon application) is re-used so it is unnecessary to revise it. However, instead of a video and a dynamically generated graphic, all of the graphics were put into the Library as Sprite classes. (To make a Sprite class just change the Base class to flash.display.Sprite.)
Read more…

Share

ActionScript 3.0 Builder Design Pattern Part II: Multiple Builds

December 1, 2009 6 comments

As a concrete follow-up to Part I of this two-part post, I thought that once I decided on which graphics, text and video to use the development would go pretty quickly. It took a lot longer than I thought, but now that the concrete example is ready it’s pretty easy to see how to put a practical Builder together and re-use and extend it. Because this second part builds on the first part, if you’re only vaguely familiar with the Builder Design Pattern, you might want to review Part I.

What to Build?

In ActionScript 3.0 Builder Design Pattern Part I, we set up a vacation-building site using trace statements to display different characteristics. To make these characteristics come alive and work in some practical matter, the goal is to create a builder that does the following:

  • Load an external graphic
  • Play a video that can be displayed in any format used by Flash Media Server or Progressive Download
  • Display a different background for each vacation destination. The background is made of an external .swf file
  • Present text write-up using external text source

In looking at those four actions, you might be thinking, that’s not exactly rocket science. You’d be right. However, when you start adding more and more vacation destinations, keeping track of everything can dampen one’s resolution. With the Builder, though, I found it very easy to add, change, and delete. In fact, I encourage you to add your own favorite vacation place and add it using the builder described in this post.

The Design

In Part I, I talked about different variations in the Builder’s design. The one we’re using closely follows the first as far as the Product class is concerned. All of the concrete builder classes use the same Product class. The Product class assembles the different parts under construction. However, in order to keep the Product class manageable, I added several Helper classes to take care of the details for the different parts that need to be built for the final product. Figure 1 shows the file pattern for the design:

<em><strong>Figure 1: </strong> File Class Diagram of Builder Design Pattern</em>

Figure 1: File Class Diagram of Builder Design Pattern

As you can see, several classes use the Product class, and it uses all of the helper classes. Even the Client holds a reference to the Product class. As far as design is concerned, though, this one is identical to the one we used in Part I with the added helper classes.
Read more…

Share
Categories: Builder

PHP Chain of Responsibility Design Pattern from ActionScript 3.0

November 15, 2009 6 comments

smallchainARE Design Patterns portable from one language to another? Of course they are. I’ve read some accounts that claim otherwise, but I’ve not found any design pattern that could not be used in any computer language that I’ve tried. (Maybe I’m just conversant in languages where design patterns do work, but I don’t think so.) Anyway, Chandima and I have been discussing doing a set of PHP design patterns, and I wanted one for a contact form I had done using PHP.

For this blog, though, I thought I’d use a translation from one of the design patterns we have on this blog so that you can more easily see the similarities and differences between ActionScript 3.0 and PHP in implementing the same design pattern.

Chain of Responsibility

As you may recall from our Chain Of Responsibility (CoR) post, the design pattern is used when you want to have a system that takes care of requests when you have different outcomes. In our original example, we added a helper class called Request, but otherwise we stuck with the basics of the CoR structure. Figure 1 shows the class diagram of the CoR we used in our initial post.

<em><strong>Figure 1: </strong> Chain of Responsibility Class Diagram</em>

Figure 1: Chain of Responsibility Class Diagram

In this particular design pattern the Client class is a full-fledged participant in the pattern. Because Client classes are request objects themselves, it may seem odd to have a Request class. Just think of the Request class as a helper class that encapsulates requests for the Client.
Read more…

Share