Archive

Archive for September, 2010

New Twist on the ActionScript 3.0 Bridge Pattern

September 30, 2010 3 comments

Bridge with a new twist

Bridge with a new twist

About two years ago I tacked the Bridge design pattern and implied (well maybe I sort of promised….) that I’d get back to the pattern and add a little more flesh to the bones. Well, I never did.

Recently, Don Cooper took a look at the pattern and came up with a slightly different twist. In Don’s own words,

Attached is my solution for the bridge pattern, based directly on your own code. I thought it made more sense in any case to keep the graphic-making code inside the implementor, and I just needed to change the return type to Shape to make it happen, along with other stuff you’ll see. I think I could also have embedded it inside a Sprite in the implementor and passed that as a return type in order to take advantage of the InteractiveObject inherited (mouse-able) functionality, if the background needed to be clickable.

You can download Don’s solution–just click the download button:
kilroy

For details on the Bridge pattern, check out the original Bridge post. Enjoy!

Share
Categories: Bridge

Saturated Strategy 2: First Implementation

September 29, 2010 9 comments

You need to add your own algorithm to understand the pattern's value

You need to add your own algorithm to understand the pattern's value

Strategy Implementation

In this second installment of looking at the Strategy pattern, we’ll take a simple application to use as a point of reference. Last time we looked at the participants, and this time we’ll begin with a simple class diagram and then implement the pattern. As you recall from the first post in the Saturated Strategy pattern series, the pattern has three participants: Strategy (an interface), Context, and ConcreteStrategy. Further, while no Client class is a participant in the pattern or even implied (shown by a ghosted class box), it is important. It provides the request for a ConcreteStrategy. However, it does not do so through the Strategy participant, but instead it goes through the Context.

The Class Diagram

At this point it makes more sense to look at a class diagram of the Strategy because you know what each participant does from the first installment of this series. Figure 1 shows the participants in a class diagram:

<em><strong>Figure 1:</strong>Strategy class diagram</strong>

Figure 1:Strategy class diagram

As you can see no Client class is included—not even the implied. So how does one go about making requests? In the first installment, you saw that the Client uses the Context class to make requests for a ConcreteStrategy. Further, the aggregation symbol (arrow with the diamond on the tail) shows a fairly strong connection between the Context and Strategy. So how do we go about implementing a basic design using the participants given in the class diagram? (Turn the page to see the first implementation used in this series.)
Read more…

Share
Categories: Saturated Strategy

Saturated Strategy 1: A Look at the Participants

September 28, 2010 2 comments

Start Here for Saturated Strategy Design Pattern

Start Here for Saturated Strategy Design Pattern

Last weekend I was somewhere south of Boston on an apple picking outting with the family, and I had to get back to Connecticut on business. From West Buckwheat (or wherever I was) I had to get to the Mass Pike and hot foot it to the Nutmeg State. Since the Mass Pike has only a few places where you can enter and exit, I had to find the wormhole that allowed me to get on the Pike from in the middle of nowhere. Recently I got a new car (2006 is new for me) and it came with a GPS system. Since I didn’t have a map I decided to trust the GPS system and set it for “Home.” Anyway, off I went through a maze of back roads that changed names every two blocks, and the trusty GPS took me right to the Pike. I thanked the GPS and told it I could take it from the Pike without further assistance, but it insisted on shepherding me home anyway. (Before I got my wife a GPS, she told me that she followed cars with Connecticut plates to find her way back from Boston–that’s why I got her a GPS!)

I digress. The point I was about to make is that one can use different navigation strategies. When I used to fly, we had VOR, Loran, ILS, radio beacon and visual landmarks to guide us around the sky. Back in the day, seafarers had sextants and compasses for celestrial navigation and dead reckoning. Suffice it to say that several strategies are available for navigation. That’s where I got the idea to create a Strategy design pattern using different navigation strategies as different algorithms. (Turn the page for the rest of the post.)
Read more…

Share
Categories: Saturated Strategy

It's the Client: Not the Main!

September 23, 2010 21 comments

mainLet’s Stop Calling the Client “Main”
At one time using Flex, it automatically generated a first file it named “main” and everywhere I look I see the client class named “Main.” Why? Naming a class that does nothing but make requests “main” is like calling the butler the ‘Lord of the Manor’ because he answers the door. In addition, it’s a little confusing because the design pattern is the main part, and that’s important to fix that idea in your head. I think there were even a few places in the Gang of Four book where they use “main” in a class that was anything but that. In discussing participants in a design pattern, you will generally find either a reference to the Client or the Client as an actual part of the design pattern. You will never see “Main” as a design pattern participant.

Everything in your life will get better if you drop naming classes “Main.” I even made a class diagram of the point as shown in Figure 1.

<em><strong>Figure 1:</strong>Why to Quit Calling the Client Main</em>

Figure 1:Why to Quit Calling the Client Main

So let’s focus on design patterns and use names that describe the roles. The term “main” is a tradition, but programming is not Fiddler on the Roof; so we can cut it out!

Share
Categories: ActionScript

Constructor Functions as Cluster Bombs

September 21, 2010 19 comments

Constructor Function Attacks Design Pattern

Constructor Function Attacks Design Pattern

Every now and again I re-visit issues in the same way one might refresh a Web page. At the beginning of the year I had a post on Constructor Functions based on Miško Hevery’s article that explained why constructor functions should do no real work. Since that time, I’ve been consciously working to keep constructor functions out of every class in a design pattern except the Client. However, in some PHP design patterns, I started removing them from the client as well. In Flash, you need some kind of self-starting class in the FLA to fire up the pattern in use, but in PHP, I found that I could instantiate the client using a little chunk of code and then use the methods I wanted to request just what I wanted. However, I’ll probably keep the constructor function in my Client class because if nothing else it can set up the UI. Then the methods (not in the constructor function) can be called as needed from the UI.
Read more…

Share

Another Approach to the Protection Proxy: Adding Helper Classes

September 21, 2010 4 comments

Protection Proxy with DataLoaded Helper Classes

Protection Proxy with DataLoaded Helper Classes

During the summer I was heads down on a book project that got more urgent as the summer progressed. As a result, I’m a bit late on a suggested revision of the Protection Proxy sent in by Gil Amran way back in June.

In the original article, I questioned the practice of hauling a reference to the output UI all the way through the program. However, focusing on the design pattern, I didn’t concern myself with certain details that would have been optimal in a larger sense. Also, I don’t like using helper classes when trying to focus on the basics of a pattern. So, I just put in bare essentials hoping that readers will better be able to see how the pattern works.

However, I’m always looking for better ways of programming, and to misquote Ralph Waldo Emerson,

Build a better proxy and the world will beat a path to your door.

So download Gil’s code, and let’s take a look at it:
kilroy

A Better Mousetrap

The revision of the Proxy was by Gil Amran and here, in Gil’s words, is what was changed:

I’ve changed few things:

  1. I used AbsSubject and not the interface. (Abstract class)
  2. I’ve overrided the clone method in the 2 custom events.
  3. I’ve re-dispatched any events that came from he realSubject

Further Gil notes,

The AbsSubject extends EventDispatcher, and there’s no way to avoid that. Because the actual loading takes time and works with events, using callbacks might be another way to solve this and not use events.

In comparing Gil’s proxy with the original, the key differences are in handling events. Figure 1 is a file class diagram of Gil’s protection proxy you can compare to the original:

<em><strong>Figure 1:</strong>Protection Proxy with Event Dispatch Classes

Figure 1:Protection Proxy with Event Dispatch Classes


The two helpers classes function to deal with event handling and dispatch.
Read more…

Share
Categories: Proxy Pattern

The Saturation Plan: One's Bound to hit the Target

September 16, 2010 6 comments

Color Saturation and Learning Saturation

Color Saturation and Learning Saturation

Saturating the Field
I was looking at John Lindquist’s fantastic video explaining the Strategy design pattern, and while I’ve been thinking about a slightly different tact for learning, it gave me an idea. Up to this point, Chandima and I have gone over lots of design patterns in varying levels of depth. However, what I think would help the developers on this blog learn design patterns would be to take just a few, one from each of the three main categories, and come at it from different angles. That is, saturate readers with lots of information and examples from just three patterns.

The Three Types of Patterns

The Gang of Four divide up design patterns into three types:

  • Creational
  • Structural
  • Behavioral

I realize that those names don’t mean jack unless they are viewed in terms of problem-solving. That is, what specific problems are addressed by each of these groupings of design patterns? So let’s start with a summary of the problems that design patterns address.

On pages 24-25 in their book, GoF discuss the common causes of redesign. What causes developers to tear apart a program and have to start over? Why can’t a class be re-used? Why can’t just a few things be changed to introduce something new? If you read those causes, you can better see the solutions to those problems. The following are the eight causes of redesign GoF specify that cause problems. Remember! This is a list of bad practices that Gang of Four have identified that prevent change and reuse of objects:

  1. Creating an object by specifying a class explicitly
  2. Dependence on specific operations
  3. Dependence on hardware and software platform
  4. Dependence on object representations of implementations
  5. Algorithmic dependencies
  6. Tight coupling
  7. Extending functionality by subclassing
  8. Inability to alter classes conveniently

Design Patterns are meant to address these various bad habits. For example, the Factory Method addresses the issue of creating an object by specifying a class explicitly. So you may be wondering—What’s wrong with that? How else could you create an object?

Most developers do not see the problem with explicit class creation. Simply stated, to do so can tangle you up in the particulars of the class. A commitment to a specific class leads to dependencies on the that class’ implementation. However, instead of committing to a class, commit only to an interface and use the other class through the interface. Then, if you want to make changes, you only have the interface, which cannot cause a dependency. Using the Factory Method, you create class instances indirectly through a factory. The factory creates the instance, and your Client uses the factory’s instance.

The Saturation Plan

To get this plan off the ground, I thought that a good place to begin would be with the Strategy pattern. The reason for choosing the strategy pattern is that because it specifically addresses more than one of the issues: Algorithmic dependencies and Extending functionality by subclassing. Everyone loves a good algorithm; but if a new one comes along that does a better job (like swapping in a Skip List for some other search algorithm), you don’t want to tear up your whole program to do so. You just want to tuck in the new algorithm where they old one was. Secondly, the Strategy pattern is one of the key patterns for using delegation. Any program that uses delegation over inheritance has fewer dependencies. Finally, the Strategy pattern is flexible so maybe developers can be weaned from the MVC long enough to get into a new pattern and move ahead in design patterns.

This is not an invitation to argue the best algorithm. For all I care, you can use a bubble sort—algorithms are not the issue. The issue is that we use and change algorithms so often that if we can do that with more flexibility; then redesign becomes easier. We’ll look at the Strategy pattern from so many different angles with several different posts, that you’ll be so inundated with it, you can’t help but understand it.

The Principles

OOP and design pattern principles are like cheat sheets to understand design patterns and become a better programmer. If you haven’t gone over them lately, they’re all here for you. Go over them, and you’ll be part of the discussion and get more out of the saturation plan.

Your Thoughts

The comment section is for feedback. I’m going to initiate the plan in the next couple of weeks, but if this is not something you feel will be of any benefit for you or you have a better idea, let me know.

Share

Measuring the Goodness of ActionScript 3.0 Design Patterns

September 9, 2010 6 comments

Why Design Patterns are Hard

Why Design Patterns are Hard

How Come they Get Calculus and We Get Sticks and Arrows?
I’m still playing with Skip Lists: A Probabilistic Alternative to Balanced Trees by William Pugh. I have yet to work up an ActionScript 3.0 solution for both inserting new data into a skip list and deleting data from one—even though there’s lots of code that shows how to do it. It’s more fun to look at Pugh’s article with the pseudo-code that he provides to show how to insert/delete data in skip lists. Were I working to figure out a design pattern, I’d be looking at a bunch of association arrows, dashed line instantiation trails and diamond-tailed aggregation spears—just like poor old wound man.

Some of the key parts of Pugh’s article, along with lots of articles you see in professional programming journals have all of these cool formulas. If you’ve seen Flash Math Creativity: 2nd Ed by Keith Peters and some other folks, you’ve seen lots of formulas like the one’s in Pugh’s article although Flash Math Creativity tends to be more trigonometry and geometry than calculus—in any case they’re über cool.

So how do we calculate the efficiency of Design Patterns? The algorithm crowd gets all kinds of cool formulas from every nook and cranny of math—even statistics in some cases. However, in going through The Gang of Four’s Design Patterns, there’s not a single formula that has that kind of proof.

Here’s What I’m Talking About…

In discussing how to work through the cost of running a skip list versus a balanced tree, Pugh offers the following formula:

C(0) = 0
C(k) = (1–p) (cost in situation b) + p (cost in situation c)

which he follows up with:

C(k) = (1–p) (1 + C(k)) + p (1 + C(k–1))
C(k) = 1/p + C(k–1)
C(k) = k/p

Eventualy he comes up with the total expected cost to climb out of a list of n elements as:

L(n)/p + 1/(1-p) which is O(log n)

In all of this, C(k) is the the expected cost —length— of a search path that climbs up k levels in an infinite list. So now Pugh can take his formula to the Balanced Tree makers, and say,

See, my formula proves that Skip Lists work as well as Balanced Trees and they take less effort.

So with formulas you can demonstrate mathematically and using math logic that a certain course of action is a reasonable one. So where do we start looking for formulas that can:

  • Help determine which pattern to use
  • Prove that a design pattern is a better choice over a non-design pattern

Why not start with OOP principles and see if they can help?
Read more…

Share