Last Updated: February 25, 2016
·
786
· elct9620

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.