/ 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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Note: * Notice that both _instance & getInstance() are static. Thus, _instance exists before * any objects of the class have been created, and getInstance() can be called for the * class and so it can be called before there are any objects. */ package mvc { import mx.collections.ArrayCollection; /* Because ActionScript requires that all constructors are public, you can't prevent * anyone from making more Model Objects. Even without an explicit constructor, it * would appear as if it can't happen but unfortunately, but the compiler will still * synthesisize a default public constructor. Thus singleton behavior can only happen * by convention and the best you can do is communicate the intent of the pattern */ public class Model { private static var _instance:Model; [Bindable] public var buddies:ArrayCollection = new ArrayCollection( [ "ChrisAIV", "Jimmy", "Sandy", "Frosie" ] ); public static function getInstance():Model { if( !_instance ) _instance = new Model(); return _instance; } } }