122 | Chapter 3: Singleton Pattern
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 running 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 ismyCart. Three values are then placed in the “cart” using thekaChing( )
Example 3-15. ShopCart.as
package
{
public class ShopCart
{
private static var _cartTotal:Number=0;
private static var _instance:ShopCart;
public function ShopCart(secure:PrivateClass) {
trace("ShopCart instantiated");
}
public static function getInstance( ):ShopCart
{
if(ShopCart._instance == null)
{
var security:PrivateClass=new PrivateClass( );
ShopCart._instance=new ShopCart(security);
}
return ShopCart._instance;
}
//Method
public function kaChing(cart:Number):Number
{
_cartTotal+=cart;
return _cartTotal;
}
}
}
class PrivateClass
{
public function PrivateClass( ) {
trace("private class installed");
}
}