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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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.
1 | var mySingleton:Singleton = Singleton.getInstance(); |
You can also use the shorthand as:
1 2 3 | public static function getInstance():Singleton { return (__instance ? __instance : (__instance = new Singleton())); } |
If you want to pass the parameters, you can do as:
1 2 3 | 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