ActionScript 3 - Singleton
ActionScript 3 didn't allow using private constructor, but if we want use single instance pattern, we need some trickly method to implement it.
package {
  class Singleton {
    private static var _instance:Singleton = null;
    public function Singleton(caller:Function) {
      if(caller != preventCreation) {
        throw new Error("This is a singleton class, please use getInstance() method.");
      }
    }
   private function preventCreation():void {}
   public static function getInstance():Singleton {
     if(Singleton._instance) {
       return Singleton._instance;
     }
     Singleton._instance = new Singleton(this.preventCreation);
     return Singleton.instance;
   }
  }
}
We just make a "private" method to limit constructor create instance directly, so we only can use getInstance() method to get instance.
Written by 蒼時弦や
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Actionscript3 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#