ActionScript 3.0 Design Patterns

(Chris Devlin) #1
When to Use the Singleton Pattern | 123

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 asTestCart.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
{
private var cartNow:Cart=new Cart( );
public function TestCart ( )
{
var myCart:ShopCart = ShopCart.getInstance( );
var apples:Number=2.45;
var oranges:Number=3.50;
var blackberries:Number=4.11;
myCart.kaChing (apples);
myCart.kaChing (oranges);
myCart.kaChing (blackberries);
var total:String=String(myCart.kaChing(0));
cartNow.total_txt.text="$"+total;
this.addChild (cartNow);
cartNow.x=(550/2)-(321.6/2);
cartNow.y=(400/2)-(316.6/2);
//Attempt to create new instance and introduce new amount
var ghostCart:ShopCart = ShopCart.getInstance( );
trace ("Ghost cart adds 25.33 for a total of $"+ghostCart.kaChing(25.33));
}
}
}

Free download pdf