nulldesign // lars gerckens » AS3 Singletons, the other way

AS3 Singletons, the other way

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.

20. November 2007 | Posted in Actionscript

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Trackback this post  |  Subscribe to the comments via RSS Feed

About

  • nulldesign is the company and showcase site of freelance developer Lars Gerckens who is based in Hamburg, Germany. I'm available for freelance work with focus on Flex, Flash and AIR development. I like to create dynamic user interfaces, cutting edge web experiences and innovative ways to visualize data.

    This site showcases some of my personal work and projects as well as an selection of commercial projects.

    If you are interested in my work or you have any questions, don't hesitate to drop me a line:

  • Profiles: Xing | Linkedin
  • Mail: lars [at] nulldesign [dot] de

Categories

Search