Posted By

chrisaiv on 10/11/09


Tagged

Singleton as3


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

peterbelsky
davidino1978
tspitzr


AS3: Singleton Explanation


 / Published in: ActionScript 3
 

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.

  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
Posted By: jasonm23 on November 24, 2009

If you create a private class (outside your package) you can use this as a SingeltonEnforcer... eg.

package mypackage
{
    public class SingletonExample
    {
        public function SingletonExample(enforcer:SingletonEnforcer)
        {
        }

        private static var _instance : SingletonExample;

        public static function getInstance():SingletonExample
        {
            if (_instance == null)
                _instance = new SingletonExample(new SingletonEnforcer());

            return _instance;
        }

}
class SingletonEnforcer {}
Posted By: chrisaiv on December 2, 2009

Thanks Jasonm23. For anyone interested, I also show another way to complete the Singleton pattern. http://snipplr.com/view/22245/as3-my-favorite-example-of-singleton/

You need to login to post a comment.