Posted By

chrisaiv on 10/31/09


Tagged

Singleton as3


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

edsonpavoni
iamgowan
thastylos
adrianparr
tspitzr
mitien
albertomori
bshantz


AS3: My favorite example of Singleton


 / Published in: ActionScript 3
 

There are a variety of ways to create a Singleton in AS3 but because Adobe wants to be ECMA compliant, there's no way to do it (like in Java) using a private constructor. Writing a singleton this way will give you a runtime warning if something goes wrong.

  1. package
  2. {
  3. public class Singleton
  4. {
  5. private static var _instance:Singleton;
  6. private static var _okToCreate:Boolean = false;
  7.  
  8. public function Singleton()
  9. {
  10. if( !_okToCreate ){
  11. throw new Error("Error: " + this +
  12. " is not a singleton and must be " +
  13. "accessed with the getInstance() method");
  14. }
  15. }
  16.  
  17. public static function getInstance():Singleton
  18. {
  19. if( !Singleton._instance ){
  20. _okToCreate = true;
  21. _instance = new Singleton();
  22. _okToCreate = false;
  23. }
  24. return _instance;
  25. }
  26. }
  27. }

Report this snippet  

You need to login to post a comment.