One of the most important patterns that we use over here is the Singleton. It’s used when you need to restrict use of a class to one or only one instance. This comes in handy when you are casting things like application wide settings, or if you are building something like a logging service. There is a bit of disagreement on the use of the singleton, but it really boils down to two questions:
Will you use this class exactly the same way?
Will you only ever need only one instance of this class?
If you answer yes to these two questions, you might have the case to build a singleton. – So here is how you go about doing it in AS3 -it’s a bit tricksy ’cause as3 has no private constructors:
Example Singleton
[as3]
package somepackage{
public class MySingleton{
private static var _instance:MySingleton;
public function MySingleton(enforcer:Enforcer){}
public static function getInstance():mySingleton{
if(MySingleton._instance==null){
MySingleton._instance = new MySingleton(new Enforcer)}
return MySingleton._instance
}
public function someExampleService():void{}
}
}
class Enforcer{}
[/as3]
So that’s the basic code structure. Some items of note is the inclusion of the empty Enforcer class outside of the package. This is critical, as you don’t want to place your Enforcer in the package or class definition of the singleton. So lets talk about how this thing works. The key is the conditional static function getInstance. It only creates the internal variable _instance if one does not already exist. In addition to this restriction, the Enforcer class will generate an error if you try to instantiate an instance of MySingleton using the new keyword. Try it…
Great…So how do you instantiate this pattern? Simple… just access the class methods through the getInstance() method:
MySingleton.getInstance().someExampleService()
Happy coding!