Using Singletons in AS3
The Singleton design pattern requires a class to have exactly one instance – preventing multiple instantiation.
The pattern is very useful – including utility classes that manage ‘one thing’ throughout the entirety of your application. Singletons are not natively supporting in AS3. Why? I have no idea. It would have been nice. Perhaps it will be included in the upcoming ActionScript 4.0 when it is released.
I show two styles. Only one style is needed. Learn each one and then choose your favorite!
Example
// TWO STYLES ARE SHOWN // ******************************************* // DEMO 1 - View the Console Output (getInstance() Required) // ******************************************* var MyCustomSingleton1 : CustomSingleton1 = CustomSingleton1.getInstance(); MyCustomSingleton1.traceTheSecretPhrase(); MyCustomSingleton1.secretePhrase = "Now the value has changed in 1."; MyCustomSingleton1.traceTheSecretPhrase(); // ******************************************* // DEMO 2 - View the Console Output (getInstance() *NOT* Required) // ******************************************* CustomSingleton2.traceTheSecretPhrase(); CustomSingleton2.secretePhrase = "Now the value has changed in 2."; CustomSingleton2.traceTheSecretPhrase(); // ******************************************* // DEMO - Impossible - This will show an error // ******************************************* //var myFailedCustomSingleton1 = new MyCustomSingleton1 (); //var myFailedCustomSingleton2 = new MyCustomSingleton2 ();
The Case Against Singletons
Not everything in your application should be a Singleton. Its a tool to be used sparingly. In face there is active debate (here, and here) if Singletons are actually the devil.
I say Singletons are NOT the devil. But don’t take my word for it see those debates.
Next Steps
- Don’t understand me? I don’t blame you. It’s crazy.
- Check out the source (See ‘Member Resources’ below) and tell me what you think in the comments below!
Member Resources
You must be a 'Free Member' to see this content. With your access you will enjoy members-only content like this, HD video tutorials, and access to complete source code.
Ready To Join?
- Sign up for 'Free Member' level now. Its free!
- Sign up for 'Paid Member' level to enjoy much, much more! (Invite Only)
- Log in and enjoy!











