AS3: Singleton Explanation


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

Apparently Singletons in AS3 is pretty controversial so rather than provide the various solutions out there, my intent was to explain why it's such a headache.


Copy this code and paste it in your HTML
  1. /* Note:
  2.  * Notice that both _instance & getInstance() are static. Thus, _instance exists before
  3.  * any objects of the class have been created, and getInstance() can be called for the
  4.  * class and so it can be called before there are any objects.
  5. */
  6. package mvc
  7. {
  8. import mx.collections.ArrayCollection;
  9.  
  10. /* Because ActionScript requires that all constructors are public, you can't prevent
  11. * anyone from making more Model Objects. Even without an explicit constructor, it
  12. * would appear as if it can't happen but unfortunately, but the compiler will still
  13. * synthesisize a default public constructor. Thus singleton behavior can only happen
  14. * by convention and the best you can do is communicate the intent of the pattern
  15. */
  16. public class Model
  17. {
  18. private static var _instance:Model;
  19.  
  20. [Bindable]
  21. public var buddies:ArrayCollection = new ArrayCollection( [ "ChrisAIV", "Jimmy", "Sandy", "Frosie" ] );
  22.  
  23. public static function getInstance():Model
  24. {
  25. if( !_instance ) _instance = new Model();
  26. return _instance;
  27. }
  28. }
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.