O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Minimalist Abstract Singleton

To illustrate the Singleton design pattern as simply as possible, Figure 3-4 uses the classic Singleton with very little change. The added else statement shows what happens when more than a single instance is instantiated at the same time. It will be removed in the remaining discussion of the Singleton. The other trace statements in the script shown in Example 3-4 help to demonstrate how the script runs through the code.

Example 3-4. Singleton.as

1 package
2 {
3     public class Singleton
4     {
5         private static var _instance:Singleton;
6         public function Singleton(pvt:PrivateClass) {
7         }
8         public static function getInstance():Singleton
9         {
10             if(Singleton._instance == null)
11             {
12                 Singleton._instance=new Singleton(new PrivateClass());
13                 trace("Singleton instantiated");
14             }
15             else
16             {
17                 trace("Sorry--already have a Singleton instantiated")
18             }
19             return Singleton._instance;
20         }
21     }
22 }
23 class PrivateClass
24 {
25     public function PrivateClass() {
26         trace("Private class is up");
27     }
28 }

Save the files as Singleton.as. You now have a Singleton to work with. The next step is actually using it.

Instantiation with a Private Class Parameter

When the Singleton class is instantiated as an object in a program, you cannot successfully use the following format:

var mySingleton:Singleton = new Singleton();

This format runs into the ironic problem of needing an argument in the constructor. Right now, the declaration line has 0 arguments, and you need 1. The argument ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required