Header image

AS3 Singletons, the other way

November 20th, 2007 | Posted by lars in Actionscript

Since you can’t declare a constructor private in AS3, there are a few methods out there to enforce a Singleton. A common way is to declare an internal SingletonEnforcer class outside the package: SingletonEnforcer, but the declaration of the Enforcer outside a package looks a bit “dirty” to me. Another way is to declare the singleton as a static variable, but this way you can’t decide when your singleton is instantiated.

So, why don’t just try nearly same with a local variable:

package {
    public class Singleton {
        private static var instance:Singleton;
        private static const checker:Object = {};
 
        public function Singleton(initObj:Object) {
            if(initObj != checker) {
                throw new Error("Private constructor!");
            }
        }
 
        public static function getInstance():Singleton {
            if(instance == null) {
                instance = new Singleton(checker);
            }
            return instance;
        }
    }
}

Update: I found another nice solution by GSkinner: SingletonDemo.

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">