AS 3 Singleton Template
March 18th, 2008
Awhile ago I read this article about best practices for creating singletons in AS 3 on gskinner’s blog. I thought I would share the template that I use for creating my utility classes.
When I need to make a new utility or any signleton I usually start with this simple class template:
import flash.events.EventDispatcher;
dynamic public class AbstractSingleton extends EventDispatcher {
public static const INIT:String = “init”;
private static var __instance:AbstractSingleton;
public function AbstractSingleton(enforcer:SingletonEnforcer) {
// Constructor
}
public static function get instance ():AbstractSingleton{
if(AbstractSingleton.__instance == null) {
AbstractSingleton.__instance = new AbstractSingleton(new SingletonEnforcer());
}
return AbstractSingleton.__instance;
}
}
}
class SingletonEnforcer {}
This is similar to example 2 from Skinner’s post. The reason why I like this version is because it still uses the SingletonEnforcer1 class like in his example but I use a getter to streamline the process of directly accessing the instance. This way it looks a little cleaner when you need to call a function on the class:
// vs
AbstractSingleton.instance().function_name();
I also like to use a shortcut varable at the head of my class like so:
var utility: AbstractSingleton = AbstractSingleton.instance;
// Function call
utility.function_name();
Feel free to modify this as you need and add a comment with how you use Singletons or Utility Classes in your own applications.
- Skinner calls his enforcer “SingletonBlocker” and declares it an internal class. [↩]











March 23rd, 2008 at 10:23 am
[...] functions and were very specific to their use; mostly functioning as utilities/helpers. In AS 3 my Singletons simply uses an internal class to keep the constructor from being called more then once. Actually, [...]