By paddloPayday loans

Archive

Archive for the ‘Abstract Classes’ Category

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

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

ActionScript 3.0 Interface: What are they good for?

December 5, 2010 20 comments

What good are interfaces?

What good are interfaces?

Let’s Be Humble

Design Patterns were founded in the context of OOPSLA (Object-Oriented Programming, Systems, Languages & Applications) gatherings sponsored by the ACM (Association for Computing Machinery) and attended by both academic and industry programmers. These are smart folks in the world of computing, but as I’ve mentioned on other occasions, they are far less arrogant and more willing to listen to others—especially if those others listen to them in turn. Everyone assumes that everyone else is knowledgable and if they have a question, they get a straight answer–not a I’m smarter than you answer, but an-answer-to-the-question-asked kind of answer. I appreciate that because I’ve got a lot of questions.

At the last OOPSLA meeting (now called SPLASH), I got into an argument with a programmer and we both got our backs up. However, we both realized that the other was sincere, and we both shared the common goal of learning more about the topic; and the result was that she and I learned from one another. Mostly, I just ask straight questions and get straight answers—or give them. Sometimes mine or others answers may clash, but that’s what happens when you share ideas.

Now to the point. The other day I was snooping around the internet for a good distinction between abstract classes and interfaces and I came across a link to a blog that promised such a distinction. In discussing the distinction, the blog’s host first went on a long-winded detour to tell us how smart he was and how he used a “test question” to queries about programming. The “test question” was to distinguish between abstract classes and interfaces. His “answer” was hopelessly vague and muddled. What a jerk!

So, I am going to try and come up with a clear idea of what a class interface is and why we should care about it. I’ve included an interface example further on in the post, but you can download the files here:
kilroy

Straight Answer to “What is an Interface?”

In our book on page 19, the section, The many meanings of interface, differentiates between user interfaces and object interfaces and notes that the ActionScript 3.0 keyword interface that is used to declare an interface structure is yet still another type of interface. Essentially, an interface is an abstract structure with a list of unimplemented methods whose signatures must be used in any implementation of the interface. That’s about as clear as mud in terms of what an interface is used for. It’s a straight enough answer, but clarifies nothing, nada, nichts, rien, niente.

In attempting to arrive at a good answer I looked at the Adobe documentation, and while I found nothing inaccurate and lots of examples I found nothing clarifying. So, I decided to back up and look at the more general concept of interface. One that we all seem to know and understand is that of a user interface. An interface that allows users to communicate with a computer program is a user interface. A simple example is a button. If I click a button, I can interact with the program—it is the interface. Click the button below to see what I mean:
interfaceBtn

Essentially, you were able to “touch” the program to make it do something. Okay, so we know a user interface is between the user and the computer’s program. Likewise, a TV set is an interface between a user and television programming across the airwaves, via satellite or from cable.
Read more…

Share

Design Pattern Principles for ActionScript 3.0: The Dependency Inversion Principle

bucketruleMost of what we mean by the Dependency Inversion Principle has been discussed either in describing what a design pattern does in terms of relating components to one another or implied in other principles. However, I’ve found that the Dependency Inversion Principle acts as a helpful reminder to keep things abstract in working with instances that request functionality or extend a base class.

Unfortunately, the concept of inversion is only half the story and is used in reference to programming structures where a higher-level module depends on a lower-level module. One might be led to believe that the inversion occurs where lower level modules depend on higher-level modules only. Actually, the principle holds that

all modules of a program should depend on abstractions

Maybe a better name for the principle would be the Abstraction Dependency Principle. In any event, program modules should all depend only on abstractions. If you look at Figure 1 you can see a simple example where a Client instantiates a concrete class but depends on the abstract class for typing. Further, the concrete classes depend on the abstract class for implementation. Aggregations and associations would depend on the abstract base class instead of the concrete classes as well.
depinversion

Figure 1: Depending on Abstractions
As you can see in both the diagram and code snippets, all dependencies are on the Abstract class. That’s what the principle means at its core. It’s not a difficult one, and it overlaps with lots of other principles we’ve discussed on this blog and in our book.
Read more…

Share

Design Pattern Principles for ActionScript 3.0: Program to an Interface; not an implementation

February 14, 2009 5 comments

bucketrule1The first principle of design patterns is,

Program to an interface, not an implementation

Simply put, the Gang of Four urges programmers to declare variables only to abstract classes and interfaces and not concrete implementations. You never want to type your instance as a concrete class derived from an interface or abstract class—only to the interface.

Okay, you may be thinking that we already covered this principle in our book. That’s true. We did in both the introduction (pp. 45-49) and in part of the chapter on the Observer design pattern (pp. 285-288.) We also had a lot of examples, and so why rehash the same principle here? The following reasons seemed compelling enough to warrant additional discussion:

  • Includes dynamic binding
  • Closely tied to polymorphism
  • Built into Creation design patterns
  • Easy to ‘take to work’

Before starting, we’ll use the concept of an interface to refer to programs that use either abstract classes or ActionScript 3.0 interface. So, if you see a reference to an interface, it could well be an abstract class. It’s the concept of an interface that’s important; not the ActionScript 3.0 interface statement.
Read more…

Share

Design Pattern Principles for ActionScript 3.0: The Liskov Substitution Principle

February 8, 2009 5 comments

bucketrule2Gentle Reader: Now that we’ve worked through all of the design patterns in ActionScript 3.0 from GoF (well, Builder is still in the works, but that’ll be available soon), now would be a good time start going through the principles underlying design patterns. This will be the first in that series.

The 1987 OOPSLA keynote address by Barbara Liskov contained what has become known as the Liskov Substitution Principle (LSP). Essentially, the principle holds that

If a Client is using a reference to a base class it should be able to substitute a derived class for it without affecting the program’s operation 

(Actually Dr. Liskov said something more like:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

but I’m not about to…)

If the Client has an object of a certain type, it should be able to substitute a derived object of the same type. For example, suppose you have an abstract class named Automobile and from that class you have subclasses of Ford, Toyota, and Peugeot. Your Client has an object, myAuto:Automobile. The myAuto object can be any of the subclasses, and if a substitution is made for any one of them everything keeps on working without a problem and the change is unknown to the Client. So if you substitute a Ford for a Toyota, the Client can work with the objects without having to adjust for the change. What’s more, if you want to add a Fiat class as a subclass of Automobile, the myAuto object handles it with nary a whimper.

The one caveat is that the subclasses must all honor the contractual conditions of the parent class. So, any methods in the parent class must be functioning in the subclass (aka, derived class.)

Now you may be thinking, So what? If you’re at all familiar with other principles of OOP and Design Patterns, this principle may sound vaguely familiar, but what is the importance of this concept/principle/idea? It is this: Because the Client is unaware of the concrete class that the object may implement, the structure is far more resilient. Not only can the same structure be reused, it can be changed, updated and generally fiddled with without easily breaking anything. (Think of adding more car manufacturers to the Automobile class.) As far as the Client is concerned, as long as the interface rules are followed with the object, everything is hunky-dory.
Read more…

Share

ActionScript 3.0 Abstract Factory Design Pattern: Multiple Products and Factories

January 25, 2009 18 comments

This is one of the few design patterns that I worked up directly from the class diagram and from concepts in GoF. Normally, I like to look at some examples, done in Java or C#, but not this time. As you will see in Figure 1, the pattern appears to be fairly daunting, but I found it to be eminently practical, and it seemed to be a direct response to questions that I had about the Factory Method design pattern (See Chapter 2 for an in-depth explanation of the Factory Method.) You can download the entire example here before continuing if you wish.

 Let me start with the gist of the example from GoF and provide something more concrete that’s likely to be a typical kind of issue Flash and Flex developers deal with. Imagine a project where your designers have created general templates for a business site and another for a game site. Their templates include a SWF background and a set of buttons for a UI. The buttons are wholly programmed and require nothing in the Library, and so using them for either Flash or Flex is fairly simple.

 You want to keep your design loose, and so you decide that a factory will be helpful. However, clearly you will need a factory to create instances of both buttons and the background template. Further, you want your products to derive from an abstract class to give you as much flexibility as possible. In the example here, you will need an abstract product for buttons and another for backgrounds. You also want your factory abstract enough to make requests for sets of objects from the different products. For example, you want your factory to deliver both a set of buttons and a background that are matching pairs. You don’t want a set of buttons for a game site with a background for a business site, but rather you want the buttons to match your background—business buttons with a business background and game buttons with a game background. This is a job for the Abstract Factory.

 Figure 1 shows the class diagram. In looking at the “create” lines (dashed lines), think of them as working with matched sets. The Client requests a business set; and it gets both a business product for buttons and another product for background. So while the diagram may look busy, it really is doing something that makes sense on a basic level. That is, the design is geared to sets; of products with factories that create the requested sets rather than individual objects.

abfactory66

 

Figure 1: Abstract Factory Class Diagram
Note that Figure 1 shows that both concrete factories create instances from each of the child classes of the two abstract product classes. You can very quickly see the practicality of this when you substitute some concrete elements for the more general conceptual names.
Read more…

Share

Take a Design Pattern to Work Part IV: Establishing a Design Pattern Foundation

January 15, 2009 4 comments

Gentle Reader: This is Part 4 of a four-part series of posts on introducing design patterns and OOP into the work place. Parts 1 through 3 will provide the context for this part. Also, taking a look at No Time for OOP and Design Patterns will give you the background on this series. As always, we invite your comments.

Note: Chandima wrote the chapter in our book on the Factory Method, and he gave me invaluable help on the main program in this post as well.

Recap

Up to this point we’ve examined a simple program that loads external text and graphics, a common ActionScript chore. In the most general terms, this is where we’ve been:

  • Part I: Identifying the problem in a current solution. Why ActionScript on the Timeline can cause problems.
  • Part II: Providing a simple OOP solution: Use of Inheritance
  • Part III: Loosening Up a programs structure: Adding a design pattern element —a simple factory

To conclude the process, we now come to the last part—introducing an actual design pattern to the work place.

  • Part IV: Establishing a Design Pattern Foundation.

Given the preceding steps, the context is now in place to add a full design pattern.

From Part to Whole

Part III introduced the Simple Factory method inserted into an existing OOP program. Now it’s time to step back and look at a design pattern en toto and instead of incrementally adding to the existing program, we will refactor the whole kit-n-kaboodle from the perspective of a design pattern.

To get started, if you’re not familiar with the Factory Method pattern, take a look at Chapter 2. In fact Chandima’s Sprite Factory example beginning on page 84 is one of the clearest and most appropriate examples that you can find of the Factory Method pattern in ActionScript 3.0. So before continuing, you might want to do a quick review of the Factory Method and take a look at Figure 1, the class diagram for the pattern. (We’ll wait for you…).

factorymethoddp852

Figure 1: Factory Method Design Pattern

As you can see, the Factory Method (simple factory) is part of the Creator interface and the ConcreteCreator. The interface is an abstract class; so at least one of the methods needs to be abstract—impossible to directly instantiate but easily overridden in a child class.
Read more…

Share