Archive

Archive for the ‘Design Patterns’ Category

ActionScript 3.0 Saturated Bridge Design Pattern 1: Intention

Independent Variationby Decoupling Abstractions and Implementations

Independent Variation by Decoupling Abstractions and Implementations

Independent Implementation?

The concept that you can decouple an abstraction from its implementation sounds flat out bizarre. Whether talking about an interface or an abstract class, how in the world is it possible to implement a concrete class that is not affected by changes in the interface? If the abstraction varies, the concrete implementation is either going to change or crash. If you use an interface, you’ll have some kind of abstract method set up that is implemented by a class using the interface and its signature. If I change the interface even minutely, something is going to change in the implementation or it will crash. Suppose I change the return type in one of the methods from a Number to a String, what’s going to happen when I run the program? It will throw an error.

For example, try the following:

?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
//Client
package
{
	import flash.display.Sprite;
 
	public class Client extends Sprite
	{
		private var doFirst:IFace;
		public function Client()
		{
			doFirst=new Imp1();
			trace(doFirst.doThing());
		}
	}
}
 
//Interface
package
{
	public interface IFace
	{
		function doThing():Number;
	}
}
 
//First (correct) Implementation
package
{
	public class Imp1 implements IFace
	{
		public function doThing():Number
		{
			return 55;
		}
	}
}

That works just as expected. No big deal, the interface implementation is correctly formed. Now, make the following variation and try it:

?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
//Modified Client to call new implementation
package
{
	import flash.display.Sprite;
 
	public class Client extends Sprite
	{
		private var doFirst:IFace;
		public function Client()
		{
			doFirst=new Imp2();
			trace(doFirst.doThing());
		}
	}
}
 
//Modified implementation
package
{
	public class Imp2 implements IFace
	{
		public function doThing():String
		{
			return "Hello World!";
		}
	}
}

The only thing that was changed was the return data type from Number to String. Here’s the Crash results:

Line 3 1144: Interface method doThing in namespace IFace is implemented with an incompatible signature in class Imp2.

So how can you have independent variation between an abstraction and its implementation?

The Bridge to the Moon

When thinking about an image for this series on the Bridge design pattern, I considered a number of bridge images. However, the Bridge intention is to,

Decouple an abstraction from its implementation so that the two can vary independently.

The idea of a bridge to the moon popped up because the earth and the moon have different orbits (and a few other things) but share much in common and exert an influence on one another. The idea of a bridge to the moon is one way to think about decoupling and connections at the same time. An even better way is to take a look at the Bridge class diagram in Figure 1:

<em><strong>Figure 1:</strong> Bridge Class Diagram</em>

Figure 1: Bridge Class Diagram

Now, when we think about decoupling an abstraction from its implementation we can see that the Gang of Four made both the abstraction and implementation abstract! The implementation in the sense that we use extend from an abstract class or implements from an interface has a whole new meaning.

When an aggregate relationship exists between two classes (or interfaces) they create something akin to a concurrent object with different implementations possible. In this case the aggregate relationship is between two interfaces (or abstract classes), and you can begin to understand independent variation. So we need to look more closely at what exactly varies.
Read more…

Share

Reuse Where Objects Change: Factory Method at Work with Lazy Instantiation

February 20, 2011 Comments off

sleepFactoryBGentle Readers: Chandima and I try different things, and this is the first time (I think) that we’ve taken an online Adobe Connect presentation and the accompanying PowerPoint slides and translated them into an article (post.) If you were able to attend the online talk, you have all of the slides along with written commentary and you can take your time to review them. Of course if you are unable to attend because it’s 3:30 am in Mumbai, this provides an asynchronous means of participating. Let us know what you think. Is it effective? Ineffective? Makes no difference? Your comments are valuable and invited.

Lazy Bones

There’re more ways than one for being lazy with design patterns. In this post we’ll look at two: First we’ll see where you can take a program based on the Factory Method and reuse it for another program. Secondly, we’ll see where we put lazy instantiation in a Factory Method. That’s double lazy! So Homer Simpsons of the world unite! This is the design pattern for you. D’oh! (In the past we’ve examined lazy initialization, but in this post we’ll look at lazy instantiation.)

Last week we had our first online presentation thanks to the Adobe users in Brazil. However, many missed it, and I promised to provide everyone with the materials we covered. Besides, since this is a discussion of a Factory pattern we can reuse our Factory Button! (Even this post is lazy!) Click the two buttons to see the apps with two different implementations. Then you can download the two apps and the PowerPoint file from the presentation by clicking the download button.

Southern Brazil

Southern Brazil

 
New England

New England

kilroy

So you may be thinking that both of the applications are doing pretty much the same thing—placing objects on the screen. That’s true. Rocket science it’s not. However, the nature of the classes is such that we have a wide range of options with the objects. As the applications are currently laid out, it’s easy to change the objects and the collection of objects without breaking the application. Let’s see how.
Read more…

Share

How to Choose an ActionScript 3.0 Design Pattern Part 1: Understanding the Fundamentals

February 6, 2011 5 comments

How do I choose a Design Pattern?

How do I choose a Design Pattern?

Which Design Pattern?

One of the most persistent questions that we get is, How do you select a Design Pattern?, and usually, my response is, Decide what varies and see which pattern handles that variation. Of course, we find that lots of things vary, and deciding which one to build a design pattern around can be tricky. Furthermore, GoF have lots more to say about how to go about choosing a design pattern than just encapsulating variation. This series will cover the different criteria so that we can get a complete picture of the selection process.

Gamma, Helm, Johnson and Vlissides (aka Gang of Four) provide six criteria for making a selection (pp.28-30). They include:

  • Consider how design patterns solve design problems
  • Scan Intent sections
  • Study how patterns interrelate
  • Study patterns of like purpose
  • Examine a cause of redesign
  • Consider what should be variable in your design

Many of the selection solutions that GoF offer are simply references to a part of their book that discusses what design patterns do (which you may not have yet read), and so I’m going to try and summarize each of these criteria. That may result in an oversimplification, and you’re welcome to point out any such misstep I make and set me straight if you believe that a summarized explanation is too terse. (Better yet, go over pp. 11-31 and read all of the detail yourself.)

Consider how design patterns solve design problems

Section 1.6 (pp. 11-28) of Design Patterns is laden with major concepts and information about design pattern use as a strategy for solving design problems in programming. The foundation in finding an appropriate object is the idea that,

objects package both data and procedures that operate on data, and the only way that an object performs an operation is when it receives a request from a client.

Implied in that idea is that an objects’s internal states are encapsulated. You know what that is, and so we can move on to the central OOP issue of decomposing a system into objects. How do you do that? It’s not easy because you have so many factors to consider (some of which may be conflicting) in the decomposition process.

<em><strong>Figure 1:</strong>Decomposition is breaking down a big ugly problem down into objects</em>

Figure 1:Decomposition is breaking down a big ugly problem down into objects

So what is the decomposition process? Basically, it’s breaking down a big ugly problem down into smaller, more manageable units—in this case, classes, (objects). (See Figure 1)

Beginning with the problem (e.g., How to make a game, how to create a UI for an online store, how to make a video player), you have to decide the way in which you want to break it down. (It’s not going to break itself down!) The only thing that has ever worked for me is knowing exactly what I want to do. In other words, you need some serious understanding of the problem itself. So even before you begin to work through the decomposition process, you need to study the project you want to complete. The OOP process for decomposition has different approaches:

  • Write a problem statement and create classes and operations from nouns and verbs in the statement.
  • Focus on the collaborations and responsibilities in the system (problem you’re trying to solve).
  • Model the real world and translate the objects found during analysis into design.

At one time or another, I’ve used all of these approaches, and they all work. Usually, I find myself going between them, combining them—shaking the box with the problem inside to see how things settle at the bottom. However, it’s difficult to provide a generic case, and so I’ll provide two cases that I actually worked through.
Read more…

Share

ActionScript OOP and Design Patterns: Why Bother?

January 30, 2011 21 comments

evolution
At a workshop not long ago I found myself saying,

I’ve got nothing against 4th Graders.

It was in relation to the MVC, which is the precursor to the Gang of Four’s catalog of patterns, but it’s appropriate in this discussion as well. Originally, I was asked what I had against MVC, and I said, Nothing, and I’ve got nothing against 4th graders either. The reference was to getting stuck in the MVC in a continuous loop—just like getting stuck in the 4th grade. The MVC is brilliant because it helped free programmers from monolithic conceptualizations in programming. However, it’s a starting point; not an ending point. The Pure MVC advocates certainly agree with that idea, and that’s fine, but pure or (impure?) MVC, it’s still an MVC. The GoF make the point that different patterns can be developed around what varies in an application, and the MVC is a way to deal with UIs and has much in common with the Observer pattern; which leaves some 20 other patterns that focus on different variations. (Later developments of the MVC have elevated it to an architecture.)

In my own case, I got stuck on the State pattern for about a year and decided that it was time to move on after realizing that other patterns would serve me better when something other than state varies. Redoing my Web site now, I wish I had used design patterns in more than the video player I made with a State pattern.

Why OOP? What’s Wrong with Sequential Programming?

First off, let’s get straight what we mean by sequential programming. In one context, it means Not Parallel Programming or Not Concurrent Programming. Just ask anyone at Intel. They think that everyone should learn concurrent programming based on the fact that their processors are all multi-core, and single core processors have gone the way of the Dodo bird. They’ve got a point. In looking at my collection of computers my old Win XT may be single core, but I’m not even sure that’s it’s not a dual core. My Macs and Win 7 (64-bit) systems are all dual or quad core. (See Joe Duffy’s book, Concurrent Programming on Windows for about 1,000 pages of info on this kind of programming.) Just to be straight about the point, that’s not the kind of sequential programming I’m talking about.

In this post, I’m referring to non-structured programming where you just write one line after another. When I used to write assembly language programs (especially using the assembler I wrote myself) everything was non-structured. Likewise, a lot of the Basic programming I wrote was sequential along with Fortran and non-Pascal stuff. If I had to put a date on it, I’d guess such programming is about 60-70 years old. It’s not old school; it’s just old.

What’s wrong with sequential programming? Is it slower? Does it not execute correctly? Are there algorithms I cannot write with it?

No to all of the above.

It’s main shortcomings center around the spaghetti factor. After not too many lines of code, it’s easy to get tangled up. If your programs are short, you’ve got little to worry about with good ole’ sequential programming. Otherwise, sequential programming is difficult (near impossible) to maintain, change and keep straight.

However, you’d be amazed by the number of programming books that still present coding in nothing but sequential structure—which is non-structured. (In the past I’ve been guilty of the same thing; so I’ll be throwing no stones.) Some authors who have attempted to do otherwise have been snarled at…What about the beginners? What about the non-developers?! Grrrr! So it’s not just complacent code-writers who create programs in nothing but sequential structures; some authors do the same.

To be fair, a lot of the code in computer books is presented in snippets—little bits of sequential code to explain the syntax or to provide a working example. That’s fine and not what I’m talking about. In good books all of the bigger examples are in OOP or at least procedural programming. What I’m talking about are books where everything in the book is presented as sequential programming. One I have in mind showed a three-tiered if statement that was part of a bigger sequential monstrosity. How that mess helps beginners is beyond me. (By the way, the particular book I have in mind was published in 2009 by one of the most reputable computer book publishers in one of the most respected series.)

Oddly I found that by working with design patterns I end up doing simple sequential snippets—none of the messy spaghetti stuff. Read on to see why.

Read more…

Share

ActionScript 3.0 Saturated Abstract Factory 6: The Abstractory

January 23, 2011 5 comments

Bringing together Abstract Factories and Families of Products

Bringing together Abstract Factories and Families of Products

Every Family Needs a Factory

In the last installment of the saturated Abstract Factory, you saw that unlike the Factory Method where a concrete factory instantiates a single concrete product, the Abstract Factory instantiates a family of products. In this final post in the Abstract Factory saturation series, you will see how the factories (creational classes) create more than a single product. Each of the concrete creational classes instantiate two or more concrete products that have different product interfaces but are “joined in instantiation” by the individual concrete factories that share a common interface. In effect, the family planning is done by the Abstract Factory interface, and not the Product interface. Click the factory button to play the final product of this series and the download button to get all of the files we’ll be looking at:
factoryBtnkilroy

Before continuing take another look at the full class diagram of the Abstract Factory design pattern in Figure 1:

<em><strong>Figure 1: </strong>Abstract Factory Class Diagram

Figure 1: Abstract Factory Class Diagram

First, consider the way that the Abstract Factory interface contains methods for instantiating more than a single product. Each concrete factory instantiates a minimum of two products. It is like the Factory Method, but each concrete factory only instantiates a single product in the Factory Method. The Abstract Factory creates Multiple products.

<em><strong>Figure 2:</strong> Think of Ganesha when considering the role of the busy Client</em>

Figure 2: Think of Ganesha when considering the role of the busy Client

Second, consider the role of the Client. The Client is included in the class diagram as a full-fledged participant, and it holds references to the abstract factory interface and to the abstract product interfaces. It is not unlike the Hindu god, Ganesha who has four arms to handle all of the different client references and is also the Remover of Obstacles—and we all know there are plenty of obstacles in learning design patterns. Importantly, the Client holds references to the interfaces of both the factory and the products. By only referencing the interfaces, the Client is loosely bound to the factory and products thereby allowing for easy update and change. While it looks a bit complex, the pattern actually simplifies a complex process.
Read more…

Share

ActionScript 3.0 Saturated Abstract Factory 4: What's a Factory?

December 13, 2010 9 comments

AbFactory4Abstract What?

I like factories. When the Client makes a request through a factory, it decouples the Client from the process of creating the requested service. That means I have no worries about the building process; I just ask the factory, and it takes care of everything. After all, why should the client be involved in the creation process? When I buy a car, I don’t have to be involved in the process of building the thing. Even if I have to specify that I want a certain color, upholstery and an auxiliary port for my mobile device, I don’t have to actually build anything. I just let Ford, Tata, Nissan, Morgan, or Mercedes build it and I drive it.

To get started, let’s take a look at a three-way relationship between the Client, the Factory and the Product. For the sake of simplicity and for keeping our eye on the relationship between objects, let’s make a simple product—a shape with two parameters; one for fill color and one for stroke size. The product will be a graphic circle, the client requests what it wants from the factory, the factory gets the product with the specifications and returns it to the client. Click the factory button to see what it does:
factoryBtn
(Note: Please do not play with the circle for more than 2 minutes. You have more mysteries to uncover!) Go ahead and download the code:–>kilroy

The Product

In any kind of factory relationship, you have what is produced (product) and the producer (factory). The client request is to the factory to create one or more instances from a product class. So, the first step is to establish a class that includes all of the product ingredients. The following class has all of the ingredients for creating a circle; so it is the product class.

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package
{
	import flash.display.Shape;
	public class CircleProduct
	{
		private var perfectCircle:Shape=new Shape  ;
 
		public function productSpecs(color:uint,lineW:uint):Shape
		{
			perfectCircle.graphics.beginFill(color);
			perfectCircle.graphics.lineStyle(lineW,0x0000cc);
			perfectCircle.graphics.drawEllipse(0,0,150,150);
			perfectCircle.graphics.endFill();
			return perfectCircle;
		}
	}
}

The class has a single property, perfectCircle, a Shape instance and a single function, productSpecs(). In effect, when an instance of the class is instantiated, the instantiation process produces the product in a way communicated through the parameters. In this case, the color and lineW width are determined by the calling object—the factory. So, next take a look at the factory class.
Read more…

Share

ActionScript 3.0 Saturated Abstract Factory 2: What's Wrong with Inheritance?

November 21, 2010 7 comments

Favor Composition over Inheritance

Favor Composition over Inheritance

Doing Composition
The essence of the Abstract Factory Design Pattern is to create compositions for the Client. In the class diagram shown in Part I of the Saturated Abstract Factory series, the Client looks like a juggler pulling in different parts that are composed into a functioning component. (“Components” in this context are objects created using composition.) In order to understand and appreciate composition, we need to start with that fundamental OOP concept inheritance.

Inheritance in OOP

Ever since The Gang of Four put forth the pithy dictum,

Favor object composition over class inheritance,

OOP programmers have decidedly shifted in the direction of creating programs using composition more than inheritance. Further, any inheritance is fairly shallow with an abstract class as a parent that doubles as an interface.

However, inheritance is a core concept in OOP, and it’s not something that should be dismissed lightly. Further, in going through the design pattern catalog that Gamma et al have compiled, you will see a lot of inheritance in the class diagrams. Lest we not throw out something useful, let’s look at a simple example of using inheritance. (You may want to download the files and look at the static outcome first using the buttons below.)
kilroyplay

The Architect

Suppose I want to create an architect program that I can use to create different shapes. In fiddling around I create a class with Sprite and Shape properties along with a method that builds and returns a rectangle. In order not to embarrass myself too much, I make an effort to use a decent color scheme; so I visit kuler.adobe.com and select a color pattern named moderne interieur. I then create a base class I name Architect shown in the following listing:

?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
package
{
	//Colors: F5F4E1,D6C9B5,B4AA97,D44917,82877A
	import flash.display.Sprite;
	import flash.display.Shape;
 
	public class Architect extends Sprite
	{
		protected var foundation:Sprite=new Sprite();
		protected var archGraphic:Shape=new Shape();
 
		public function buildBox(ex:Number,wy:Number,
		          len:Number,hi:Number,
		          fill:Number):Sprite
		{
			archGraphic.graphics.beginFill(fill);
			archGraphic.graphics.lineStyle(2,0x82877A);
			archGraphic.graphics.drawRect(ex, wy, len, hi);
			archGraphic.graphics.endFill();
			foundation.addChild(archGraphic);
                        return foundation;
		}
	}
}

Anticipating that I may want to extend the class, I made the main properties protected so that any child classes can inherit them and preserve as much encapsulation as possible. However, the rectangle-building method must be public so that it can be used by clients outside the class. Further the line around the rectangle is hard-coded to a given width and color, but otherwise, it’s fairly flexible. All of the other dimensions of my rectangle are entered through a parameter. Finally, the image is stuffed into a Sprite object and then returned.
Read more…

Share

ActionScript 3.0 Saturated Abstract Factory 1: Wholesale Creation

November 7, 2010 3 comments

This is the First in the Abstract Factory Saturation Series

This is the First in the Abstract Factory Saturation Series

The Creational Patterns

To understand the Abstract Factory design pattern, we need to begin by understanding the whole category of Creational Patterns and what the Gang of Four means by creation. On pages 63-64 of our book and pages 81-85 of GoF, you will find more details about creational patterns, and here I’d like to just touch on some of the key points. Also, Chapter 2 of our book, is an excellent chapter (written by Chandima) on the Factory Method Pattern that introduces the whole concept of factory. And of course you may want to look at our original post on the Abstract Factory design pattern.

When You Depend on Object Composition

One of the first and recurrent principles of design patterns is to favor composition over inheritance. As your programs come to depend more on object composition, you need to think more about creating components required for a task. To a large extent, the creational patterns are designed for composing. GoF note that as the emphasis shifts from inheritance towards composition, other changes occur.

…emphasis shifts away from hard-coding a fixed set of behaviors towards defining a smaller set of fundamental behaviors that can be composed into any number of more complex ones. Thus creating objects with particular behaviors requires more than simply instantiating a class. pg. 81

The result of this shift can be found in two recurring themes in creational patterns:

  • Creational patterns encapsulate knowledge about which concrete classes the system uses.
  • Creational patterns hide how instances of these classes are created and put together.

If loose coupling is the overriding theme of design patterns; then creational patterns show us how to create loosely coupled objects and use them in a composition rich application.
Read more…

Share

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

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