AS3: My favorite example of Singleton


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.