• Aucun résultat trouvé

Using Multiple References in a Shopping Cart

Dans le document ActionScript 3.0 Design Patterns (Page 142-150)

This final example of a Singleton design pattern shows how a Singleton instance can have multiple references and still maintain accuracy. Like the previous examples, this one’s also simple, with the focus on both the role of the Singleton design and some insights into the Singleton structure

The online Shopping Cart is really nothing more than a conceptual image of a digital accumulator. As each new item is added to the cart, the most current entry is accu-mulated, and at the time of checkout, this total is computed with applicable taxand

playTune.playMe ("blues.mp3");

}

function doTwo (e:MouseEvent):void {

playTune.playMe ("class1.mp3");

}

function doStop (e:MouseEvent):void {

playTune.stopMe ( );

} } }

Example 3-14. DoMusicBtn.as

shipping costs. It constitutes a good example of how a Singleton should be used, because you want to be sure there’s only one shopping cart, and no matter where you add an entry, or take something out, it needs to be from the same instance.

To get started, Example 3-15 shows a Singleton design with a single method for add-ing to a runnadd-ing total. Open a new folder, copy the code from Example 3-15, and save the file asShopCart.as.

Like the previous examples, this one uses a private static variable in a method. The variable,_crtTotal, is incremented using a compound operator, and then returns the current amount when thekaChing( ) method is called.

To see the value of a Singleton structure in this application, the script in Example 3-16 generates an instance with two reference names. The first reference name is myCart. Three values are then placed in the “cart” using the kaChing( ) Example 3-15. ShopCart.as

public function ShopCart(secure:PrivateClass) { trace("ShopCart instantiated");

}

public static function getInstance( ):ShopCart {

public function kaChing(cart:Number):Number {

method, and the output is placed into a movie clip’s text field. Then, a second cart, namedghostCart, uses the Output window to add to the sum already placed in the movie clip shopping cart. As you will see, the second name reference is using the same instance because all that happens is that theghostCartinstance’s value is added to the value in the graphic shopping cart, and displayed in the Output window. This clearly demonstrates the unity of the single instance, and ensures that even with a second cart reference name, the total will be correct. Enter the script in Example 3-16, and save it asTestCart.as in the same folder as theShopCart.as file.

The final task is to create a movie clip and text field on the stage to represent our shopping cart. While it’s fairly easy to code a text field and place it on the stage, it’s a little more difficult to draw a shopping cart using code exclusively. Of course, that’s one of the nice features in Flash. You can create images, and control those images with code. Because this step involves a little more than just entering a Document class name, use the following steps to create the shopping cart module:

1. Open a new Flash document, and save it as TestCart.flain the same folder as yourShopCart.as file.

2. With the drawing tools, draw a shopping cart. Using static text, label the middle of the cart, “Total.” Select the completed shopping cart, and press the F8 key to Example 3-16. TestCart.as

package {

import flash.display.Sprite;

public class TestCart extends Sprite {

open the Convert to Symbol dialog box. Type Cart as the Name, and select Movie clip as the Type. Click the Export for ActionScript checkbox, and click OK. (See Figure 3-7 for a visual idea of the cart.)

3. Double-click the Shopping Cart movie clip on the stage to open it for editing. Use the Text tool to add a Dynamic text field. Give it the instance nametotal_txtin the Properties panel.

4. Exit the Symbol Editing Mode by clicking on the Scene 1 icon. Delete the movie clip from the stage. (Don’t worry; it’ll still be in the Library panel.)

5. Test the application by pressing Ctrl + Enter (Command + Return on the Mac.) When the application runs, it creates a singleShopCartclass instance, and, using the kaChing( ) method, it adds a total of $10.06 to the text field in the shopping cart movie clip as shown in Figure 3-7.

Figure 3-7. Correct results with two references to a single instance

Figure 3-7 also shows the Output window with the ghostCart instance adding another $25.33 for a total of $35.39. The final total is simply the sum of 25.33 and 10.06. The $10.06 value is the amount in the myCart reference, and, added to the amount in theghostCart reference, we arrive at 35.39, just as predicted.

Summary

The Singleton focuses on ensuring that only a single instance of a class is instanti-ated and having global access to the class of the Singleton’s origin. While certain aspects of the Singleton appear simple, other features show it to be a subtle and com-plexdesign pattern. To be sure, one can find more than one way to design a Single-ton, and the ones developed for this chapter certainly have no claim to originality.

However, they do represent a very standard implementation of the Singleton, and one that resolves some of the unique elements of ActionScript 3.0 specifically, and ECMAScript more generally.

The Singleton, especially the “classic” model on which we based the ones used in this chapter, has well-reasoned detractors. A short search of design pattern books and articles, including many excellent ones available online, finds many different ideas of how to best design a Singleton class or wholly replace it with a different con-ceptual structure. The fact that the Singleton provokes such thought has merit in its own right, and we certainly have wrestled with certain limitations ourselves. So if you’ve got a better Singleton design or better alternative, by all means pursue it.

The most common complaint about the Singleton is its incorrect use, or use in a con-text where it gets in the way of flexibility and reusability. Another complaint is that the pattern’s overused. Some of the overuse can be attributed to its simplicity, but overuse also happens when people don’t fully understand the pattern. One reason we provided so many different examples of the Singleton is to show that it does have clear uses. As a rule of thumb—do not use the Singleton where a good deal of change and reusability are likely. A Singleton’s purpose is clear—limiting one and only one instantiation, and providing a global entry point. Beyond that, they have limited util-ity, and while popular as part of more robust design patterns, you must be careful not to let them get in the way of another pattern’s utility.

However, as we have demonstrated in this chapter, the Singleton has some very prac-tical uses, and you should never lose sight of that. Like all design patterns, the Single-ton’s only redeeming purpose is to accomplish certain recurring programming tasks.

The fact that you can’t use it every time these tasks appear to be necessary does not mean it’s been rendered obsolete. Rather, it means simply that the Singleton isn’t the best way to do it. These tasks, especially common ones, should either serve to prompt adaptation of the Singleton, use another design pattern, or develop and adjust certain aspects of the classical Singleton design.

PART III

III.

Structural Patterns

True ornament is not a matter of prettifying externals.

It is organic with the structure it adorns, whether a person, a building, or a park.

—Frank Lloyd Wright The importance of certain problems concerning the facts will be inherent in the structure of the system.

—Talcott Parsons (20th Century Sociologist) If the structure and the program components were well chosen, then often many of the constituent instructions can be adopted unchanged.

—Niklaus Wirth Structural patterns are strategies that use classes and objects to build larger struc-tures. In part, the process entails using abstract classes as interfaces, with derivative classes making up the larger structures. Using both inheritance and composition, the Structural patterns provide rich flexibility for designing applications. The class pat-terns tend toward using inheritance in generating larger structures, and object struc-tures tend to be built using composition. However, both kinds of approaches have the same general approach. Figure Part III-1 illustrates the overall Structural pattern.

As a mental image, you can think of constructing applications with Structural pat-terns as pulling parts out of different bins. The bins represent different class exten-sions and object compositions. The structure itself is built from the parts gathered from the bins, but it becomes a new phenomenon distinct from the parts used to build it.

This section examines three different Structural patterns. First, the Decorator pat-tern adds responsibilities to an object. A single component is wrapped with new functionalities and properties while remaining fundamentally unchanged as far as its internal structure is concerned. The Adapter pattern provides a way for two unre-lated interfaces to work together. When adding a new object to an otherwise incom-patible structure, the Adapter is an alternative to rebuilding an application from scratch to accept a new feature. You will find out how to create Adapter applications

using both inheritance and composition. Finally, the Composite pattern composes objects in a tree-structure. In this way, clients can treat objects and composition (of objects) in the same way. By structuring objects in this way, the Composite pattern greatly simplifies creating complex structures.

Chapter 4,Decorator Pattern Chapter 5,Adapter Pattern Chapter 6,Composite Pattern Figure Part III-1. Structural design pattern

Structural Patterns

Class/

Object/

Interface

Class/

Object/

Interface

Class/

Object/

Interface

Class/

Object/

Interface

Larger structures are created by multiple inheritence and composition

Chapter 4

CHAPTER 4

Dans le document ActionScript 3.0 Design Patterns (Page 142-150)