How to implement singleton pattern in actionscript 3
In actionscript 3 one can not use private scope for constructor and you need a workaround to implement simgleton pattern. Following is one way that I use
package { public class Singleton { private static var instance:Singleton; private static var isAllowedInstance:Boolean; public function Singleton() { if (!isAllowedInstance) { throw new Error("Please use " + "Singleton.getInstance()" + "instead of new keyword"); } this.init(); } private function init():void { trace("init stuffs"); } public static function getInstance():Singleton { if (null == instance) { isAllowedInstance = true; instance = new Singleton(); isAllowedInstance = false; } return instance; } public function singsing():void { trace("singsing"); } } }
This will cause an error if someone uses the new keyword
var singleton:Singleton = new Singleton();
It will work fine if you use it like this
var singleton:Singleton = Singleton.getInstance();
[...] Howtos » Blog Archive » How to implement singleton pattern in … [...]