Archive

Archive for the ‘OOP’ Category

Singletons Give You Pimples: Why to Avoid the Singleton Pattern in ActionScript 3.0 Programming

November 26, 2008 24 comments

At the 2006 OOPSLA Conference in Portland, Oregon one of the people who came into our session was pounding on the Singleton Design Pattern. He even brought in a PowerPoint presentation quoting Erich Gamma as saying he wished he’d never included the Singleton in the GoF book. This wasn’t a mild rebuff of the Singleton; it was a wholesale condemnation.

The Singleton in ActionScript 3.0

A quick online search reveals a good deal of discussion about the Singleton in ActionScript 3. However, much of that discussion is based on how to improve it given AS3’s lack of private class constructors. Both Grant Skinner and Tink have provided brilliant workarounds that seem to solve the problem of multiple instantiations of a Singleton. Darron Schall has written a nice summary of the ActionScript 3.0 Singleton discussions and reached a similar conclusion as I originally did. Namely, most of the problems envisioned by ActionScript 3.0’s lack of private class constructors never caused the problems that AS3’s shortcomings were supposed to have caused. In our book, we provide a brief cautionary tale about using the Singleton, but it was not very strong or substantive. (I wrote the Singleton chapter; so I can say that.)

Any attempt to improve the Singleton is like making the black mamba more deadly. The point is not to improve it but to avoid it. However, in understanding the problems using the Singleton, we can better understand what the focus of OOP programming should be and the reason that using design patterns is important for achieving the dual goals of change and re-usability. A lot of the criticisms of the Singleton have been summarized by Scott Densmore and on the Flash-Focus blog, and my intention is not to improve on their comments. Rather, I’d like to use the general comments by them and others to focus on good practices and re-focus the discussion of design patterns to the key issues important to OOP and design patterns. That focus, I believe, is the relationship between objects.

Read more…

Share

ActionScript 3.0 Strategy Design Pattern: Under No Conditionals

November 9, 2008 9 comments

Strategies Eliminate Conditional Statements

If this entry evokes a sense déjà vu, you’d be half right. It is not another jibe to condemn conditional statements, but instead it is a discovery of another pattern where you can eliminate them. The consequences listed by Gamma, et al for the Strategy pattern includes,

Strategies eliminate conditional statements.

While I am quite familiar with the fact that the State design pattern eschews conditional statements, I was unaware that the Strategy pattern has the same feature. Rather, like everyone else I focused on the dictum, encapsulate the concept that varies when dealing with the Strategy pattern. Here I do not plan to re-hash what we covered in Chapter 11 of our book, but instead I want to look at a simple Strategy design pattern where no conditional statements are used. Also, I want to walk through a thought process when working on a simple application and show how flexible it is because of the Strategy design pattern.

It All Began with a simple MP3 Player

Creating an MP3 player in Flash is something I’ve done often and never gave it a second thought using the NetConnection and NetStream classes. However, recently I was working on one using the Sound and SoundChannel classes. Turning it on and off was trivial, but I learned that unlike the NetStream class, the SoundChannel class has no pause method. (NetStream has both toggle and non-toggle versions of pause methods.) The SoundChannel has a position property that returns the position of the MP3 file currently playing. By passing the position value to a variable and passing it to a play() method as a parameter, the play would resume where it left off. So building a player using either NetStream or SoundChannel is not rocket science.

However, suppose you decide to have a structure that could use either the NetStream or SoundChannel class. To that you might also add whether you wanted the MP3 to play on the NetStream as a progressive download or as streaming audio through Flash Media Server 3. All you have to change is the content of the algorithms to accommodate any of the three versions you envision. Of course you don’t want to dismantle all of the other work if you decide to change the program. You just need to change the algorithms.

The Abstract Architecture of a Strategy MP3 Player

When you get right down to it, you only need four algorithms:

  • Start Play
  • Stop Play
  • Pause Play
  • Unpause Play

Depending on what you have set up in the Client class for a UI and the types of classes you’re using to play the MP3 files, the details of the algorithms will vary, and you may even have a class to organize the Sound/SoundChannel or NetConnection/NetStream methods. For now, though, all I want is architecture to handle starting and stopping play and pause. This will also help reveal the structure of the Strategy design pattern. Figure 1 shows the Strategy pattern that is used in this example:
stratuncondfit

Figure 1: MP3 Player Strategy Design Pattern

The IPlayer interface is the Strategy portion of the pattern. All of the algorithms go into implementations of IPlayer, and so all we need will be four concrete strategies—one for each of the actions on the MP3 player. For this example, I’ll just use trace() statements to act as stand-ins for actual algorithms.

Context Class

The left part of the class diagram in Figure 1 is the Context participant in the pattern. As shown in the diagram, the Context class holds a reference to the Strategy (IPlayer) participant. That reference to the IPlayer can be seen in the following listing:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
 
package
{
	public class Context
	{
		protected var player:IPlayer;
 
		public function doControl():void
		{
			player.control();
		}
	}
}

Read more…

Share

Is MVC Obsolete? Flex, ActionScript 3.0 and the MVC Design Pattern

October 12, 2008 15 comments

Another View of the MVC Design Patterns

A while back Brian Lesser, another O’Reilly author and top notch Flash Media Server developer, mentioned that he did not especially care for the Model View Controller (MVC) design pattern. While he cited some references, I never paid much attention to it at the time, especially since Chandima kept writing these brilliant pieces on Pure MVC. Further, I had promised myself that I wouldn’t touch MVC until I had worked my way through all of the design patterns using ActionScript 3.0 and felt comfortable with Flex. So I really am no expert of MVC and have relied on Chandima for that particular compound design.

After weeks of pounding my head on the Prototype pattern, I was thinking of taking a break and sending a torpedo into the Singleton to let off some steam. However, before sticking my neck out (yet again) I thought I’d ask Brian why he didn’t particularly care for the MVC, resulting in a very thoughtful article. (See http://broadcast.oreilly.com/2008/10/mvc-as-anti-pattern.html) Brian asked for Chandima’s and my reaction. Not having spent that much time on the MVC, my reaction was based on the logic of the article which to me made perfect sense. However, this is a case of “What do I know?” The annual OOPSLA conference is coming up this next week and I will be bringing up Brian’s points to big brains that attend OOPSLA–and I hope some more Flex/ActionScript/Flash developers will be there this year! So maybe after next week I’ll have some comments from seriously bright programmers in addition to our seriously bright programmer, Chandima.

So take a look at http://broadcast.oreilly.com/2008/10/mvc-as-anti-pattern.html and we’d like to get any copies of your comments, thoughts, and wisdom that have you about Brian’s article to post here as well.

Share

ActionScript 3.0 Clone: A Prelude to the Prototype Design Pattern

September 23, 2008 25 comments

Where’s the Clone()?

The next design pattern I plan to tackle in ActionScript 3.0 is the Prototype Design Pattern. Getting started I ran into the clone() method in other languages like C#. As usual, that wasn’t much help. To my surprise, I found that several classes in ActionScript 3.0 have a clone() method such as the Rectangle class. However, while perfectly functional, cloning a rectangle with origins in the flash.geom namespace isn’t exactly what I had hoped for. (There’s no clone() method in the Shape class where I could make lots of clones of rectangle shapes I could put on the stage.) What I wanted was a way to clone objects.

Borrowing from Java

Buried in the Adobe ActionScript 3.0 Live Docs is a little note about cloning arrays. (see http://livedocs.adobe.com/flex/3/html/10_Lists_of_data_6.html) Using a method commonly found in Java programs, the note indicates that a deep copy clone is possible using this method. One can use concat() or slice() with no arguments to make a shallow copy. In most cases, GoF note that shallow copies will work fine, but for more complex structures a deep copy is required.

The docs list the key method as the following:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
import flash.utils.ByteArray;
 
function clone(source:Object):*
{
    var myBA:ByteArray = new ByteArray();
    myBA.writeObject(source);
    myBA.position = 0;
    return(myBA.readObject());
}

That’s a nice little piece of code and simple to understand. The clone() method creates a ByteArray that writes the object (an array) and then returns it by reading the object it just wrote. Moreover, it’s a deep copy and as such a true clone in that all of the parts are delivered and not just pointers.

Read more…

Share

ActionScript Facade Design Pattern: The Cat Herder

September 20, 2008 9 comments

The bigger and more complex a system based on subsystems gets, the more difficult it is for a client to make requests and get what is expected. The Facade acts as an interface to simplify communication with the elements that make up the subsystem and the client. So instead of communicating with all of the components of the subsystem, the client interacts with a single component, the Facade.

The class diagram for the Façade looks a good deal different from most other design patterns. The classes that make up the subsystem are intentionally vague to represent any subsystem. The problem, though, is clearly illustrated by the network of possible connections between the classes in the subsystem and how a client might run into problems when it needs to interact with them all. Figure 1 shows a modified Façade class diagram. In the original GoF diagram, the client is not listed as a participant—only the Façade and the subsystem classes. However, following the Freemans’ diagram (with some slight adjustments of my own to make it closer to the GoF diagram) I included a client but made it implicit.

Figure 1: Facade Class Diagram
Read more…

Share
Categories: ActionScript, Facade, Flash, Flex, OOP

ActionScript Proxy Design Pattern : The Virtual Proxy (A Minimal Abstract Example)

August 26, 2008 8 comments

The Gang of Four divide up the Proxy design pattern into three types: remote, virtual, and protection. In our book, Chandima and I used a remote proxy in the Symmetric Proxy example(Chapter 13). Each player in a game over the Internet was able to make simultaneous moves using the remote proxy representing an opponent on their own system. That leaves the virtual and protection proxies to cover, and we’ll start with the virtual proxy in this article.

Avoiding Repetition

Our university uses a software package called Blackboard for course administration. It’s quite handy, and I use it a good deal. As a Web-based application requiring a login, the initial login is time-consuming as the application gathers up all of the information it has stored for all of my classes. However, if I quit the program and return within a certain time window, I don’t have to go through login again. More importantly, the application does not have to reload all of the materials for me again. When you consider that hundreds of faculty and thousands of students are all using the same system on a daily basis, the ability to re-use previously loaded materials is a huge savings.

For the most part, design patterns, do not improve the performance of your programs with a few exceptions, such as the Flyweight pattern previously discussed on this blog. I believe that the virtual proxy design pattern is another one of those patterns that improves the performance of your program because your application is not constantly re-doing something expensive (time-consuming) that’s already been done. Most of the examples, including the one provided by GoF, are of loading graphics. Once loaded, most graphics do not have to be reloaded for repeated display after the initial loading. So, rather than reload graphics or files of any kind, the virtual proxy design first checks to see if your materials are already loaded, and if they are, it uses the extant materials. If not, it simply calls the real loader and loads up what’s required. Any application that has multiple users over the Web (which is most programs) the virtual proxy can significantly improve the performance of the program because it reuses loaded materials.

How the Proxy Design Pattern Works

The Proxy pattern does not have different class diagrams for the different types of proxies. Figure 1 shows the pattern diagram used for all variations of the pattern.


Figure 1: Proxy Class Diagram

The client is not a participant, but it is included to indicate where it sends its request. It is loosely coupled to the participants following the path illustrated in Figure 2.


Figure 2: Proxy Object Diagram

The proxy is used to check and see if a real subject is required, and if so, it sends the request to the real subject. However, if the proxy can handle the request without using the real subject, it will do so. In effect, the proxy acts like a gatekeeper. It inspects all requests, and if it can deal with the requests it does, but no requests go directly to the real subject from the client. Figure 2 shows the intermediary position of the proxy. The only problem with the object diagram is that it looks like the proxy is a stop along the way to the real subject, but depending on the application, the request may never get to the real subject.
Read more…

Share

An ActionScript Bridge Design Pattern: Flexibility Making Backdrops

August 22, 2008 9 comments

Like most of the design patterns we’ve dealt with both in our book and on this blog we like to start with a minimalist example and then provide a more concrete and useful example. With the Bridge design pattern, the example is fairly minimalist, but it has been designed to create graphic backdrops for video objects. So, while not exactly minimalist and certainly not abstract, the Bridge example here is still fairly simple. (Well, at least as simple as design patterns ever get.) Besides, it accomplished something I needed.

Bridge Over Untroubled Waters

With most design patterns I’ve found that their abstract concepts are clearer than their actual creation. (The Mediator design pattern in this blog is a good example.) However, with the Bridge, I found that the concept was a bit muddled, but making a Bridge design pattern that actually accomplished something useful was relatively simple. To get started, take a look at the class diagram in Figure 1:

Figure 1: Bridge Class Diagram

The intent of the Bridge pattern is to decouple an abstraction from its implementation so that the two can vary independently. (GoG 151) If you don’t think about that much, it sounds like a good idea to keep an application from grinding its gears when a change is made in either the abstraction or implementation. The Freemans (Head First Design Patterns, pp. 612-613) have a great example—a universal remote control. The remote control is the abstraction and a TV set is the implementor. Concrete implementors are the different brands of TVs. As new technology arises, the remote control can be updated with new gizmos. Likewise, the TV sets can also be updated and different brands will have their own unique features. A good Bridge design will allow each to be changed without breaking the other. So far so good.
Read more…

Share

The Mediator Design Pattern: A Minimalist Example

The Mediator design pattern is easy to understand but tricky to implement. At the core of the Mediator pattern is a Mediator class that coordinates a set of different requests that are sent by objects. The objects are called Colleagues. The Colleagues let the Mediator know that they want to change, and the Mediator handles the change taking into account what effect the changes will have on the other colleagues. For example, in my car when I turn on the headlights, the panel lights dim. Something in my car tells the panel lights to dim when the headlights are switched on. The headlights represent one colleague and the panel lights, another. A Mediator tells the panel lights to turn on as soon as I start the car, and then when the headlights are switched on, the Mediator tells the panel lights to dim. If I turn off the headlight, the Mediator tells the panel lights to brighten up again. The colleagues never communicate directly with one another but instead through the mediator. The idea is to reduce the complexity by handling all of the requests in one place. This also insures loose coupling between the colleagues.

Put succinctly, the Mediator defines an object that encapsulates how a set of objects interacts. (GoF, 273). At the bottom of justifying such an encapsulation is the fact that a loosely coupled design often has many of the objects communicating with one another. The more loosely coupled, the greater the need to communicate. This can get messy if every object is telling every other object its current state and requesting them to adjust to whatever state they are entering. This would be like my headlights communicating directly with my panel lights letting them know whether they are on or off so that the panel lights can make the necessary adjustment. Add other “interested” objects, and pretty soon you have a rat’s nest to coordinate. In order to solve this dilemma, make a cleaner design and ease the interaction, the Mediator is introduced. (Before starting the project, you might want to download the files by clicking the Download button.)

download

The Mediator’s Structure
To get started, the GoF present both a class and interactive diagram and we’ll do the same here in Figure 1:

mediatordiagram

Figure 1: Mediator Class and Interaction Diagrams

As the class diagram shows, two abstract classes, the Mediator and Colleague, each have concrete subclasses. However, a better view can be seen in the interaction diagram. You have a single concrete Mediator handling the interaction between several colleagues. In some cases, the interaction is one way and in others, two-way, but the Colleague instance always has an object reference to the Mediator. The Mediator may or may not have an object reference to the concrete colleague.
Read more…

Share

ActionScript 3.0: Not at the Children's Table Anymore

Let’s Not Perpetuate Misinformation

I’ve seen comments and blogs where the misinformed are leading the uninformed. The gist of the comments is of the nature that some ActionScript 3.0 design patterns are derived from Java or C# (or some other language.) Well, that’s like saying Java, C#, C++ and other languages got their patterns from SmallTalk. I’m sure that anyone who has begun with a design pattern for the first time needed to look at examples to get another view of the structure apart from a chart diagram. For those who used Gamma, et al for their starting point (which is just about everybody) then we’d have to claim that all design patterns are “borrowed” from SmallTalk. That’s just plain stupid in the context of what design patterns are all about. If no such examples, or good examples, can be found in ActionScript 3.0, then look in any other languages. The Gang of Four used SmallTalk for all of their examples. Some of these were quite helpful for finding the relationship between the classes/interfaces and can then be used to inform the developer what one might do with ActionScript 3.0. That’s it. Design Patterns are about relationships between classes and interfaces and it doesn’t matter what the language is they’re initially written in.
Read more…

Share

ActionScript 3.0 Memento Design Pattern: Flash Media Server 3 Application

January 27, 2008 9 comments

Jumping Out of Sequence: Memento Brings You Back

In the last installment on the Memento Design Pattern, you saw an abstract minimalist version to get an idea of how the Memento saved state and got it back again. I used a string variable as the “state” to be saved and retrieved without breaking encapsulation. This time around I used the Memento to solve a more practical and definitely real world problem. How to allow a user to jump around a multimedia online presentation without getting lost. To get an idea of how this works, take a look at a working example of this application at:

http://www.sandlight.com/memento/

When you run the application, you can jump to another level, and then just click the Return to Last button, and it will take you back to your jump point. Also, I put up the zip file to save time in getting all of the code in. Figure 1 shows what you can expect to see:


Figure 1

You can download it at:

Download the FMS Memento Zip File

All of the files are in Flash CS3 format, but the ActionScript files are pretty easy to port over to Flex.

Read more…

Share