This is the simplest and cleanest singleton patter I have seen to date for AS3. Let’s you set it up and get right to coding. The author does make a request for a singleton metadata tag to automatically make classes into singletons. Well we sort of have that with RobotLegs. With the injection rules you can just tell RobotLegs that any time you inject an instance of a particular class just to make it a singleton and it’ll do that in the background for you. Sweet and simple. But this code linked below is the closest non-framework solution I have seen that gets close to that in its simplicity.
It was actually a combination of other factors (and personal preference) that made me revisit the singleton pattern. The singleton technique that I prefer was developed to address the other issues I was running into and to reflect my personal coding style. While I was at it, I figured I might as well address the private constructor issue too. After all, we all love being smacked around by the compiler sometimes.
The technique I prefer has the following highlights:
- Usage of static instance read-only property instead of a static getInstance() function. This is somewhat a matter of style and personal preference, but I prefer the succinctness of the read-only property. This is especially obvious when the singleton is used in binding expressions. Plus, getInstance() is so 1990s Java which ActionScript is most definitely not. I kid, I kid. But seriously, “.instance” is cooler.
- Usage of a private lock class to prevent outside construction. While this is a common theme in the above links, my approach is slightly different. Instead of passing an instance of the private locking class to the constructor, I just pass the Class reference itself. This does two things. First, it clarifies the conditional check in the constructor. The test for the proper locking Class reference communicates the code’s intent better than the traditional check for not null. Second, it encapsulates the private locking class itself. The constructor’s argument is simply lock:Class which doesn’t expose the name of the private locking class to the outside world, but still communicates that the constructor is locked.
- Removal of ‘Unable to bind’ warnings in Flex 2. When you use a singleton in a binding expression, it’s typical to have the Console log flooded with warning messages indicating that binding to the instance property will not be able to detect updates. My singleton version fixes these warnings.
- Use of const instead of var for the instance storage. This one is pretty obvious, but using const here communicates intent better. The variable storing the singleton instance is not allowed to change so const is the better choice.