Among all design patterns, Singleton pattern is the most widely used and easiest pattern. It is very useful when combines with other design patterns like MVC. Singleton pattern provides 2 main features:
1. Only one class instance can be instantiated at any time.
2. The class has a global access point.
Consider the class below:
package {
public class Singleton {
// Properties
private static var __instance:Singleton;
// Constructor
function Singleton() {
init();
}
// Initial
private function init():void {
trace("This is Singleton");
}
// Get instance, singleton method
public static function getInstance():Singleton {
if (__instance == null){
__instance = new Singleton();
}
return __instance;
}
}
}
Use “getInstance()” class method to instantiate the class once where it will return an instance of the class which is also static property of the class.
var mySingleton:Singleton = Singleton.getInstance();
You can also use the shorthand as:
public static function getInstance():Singleton {
return (__instance ? __instance : (__instance = new Singleton()));
}
If you want to pass the parameters, you can do as:
public static function getInstance(arg:Object):Singleton {
return (__instance ? __instance : (__instance = new Singleton(arg)));
}
Remember to add arguments to your constructor too.
Happy patterning:)
No user commented in " Singleton Pattern "
Follow-up comment rss or Leave a TrackbackLeave A Reply