Monday, December 27, 2010

Singleton Pattern using flash AS3 .

please like and post your questions : http://www.facebook.com/pages/FlashCS5-Tutorials/176320862386436

The Singleton pattern is used for projects where you want to create classes that can only ever have one instance, I think usually you can use this pattern in the case you have a manager-type of class that will manage other classes objects and it can be access from anywhere in your project, or you can use it when you dont want to create  more than one instant like for example that you have a style manager for the whole application and you have one style for this application .


First of all,
you need to find a way to limit the number of instances a class can create to one. The obvious approach would be to have a property that keeps track of the number of instances a class has. Doing that, you’ll soon come across a practical problem: how can you keep count of the number of instances a class has, when class properties are defined on the class instance and not shared throughout the class?

To do this please have a look to the following Singleton Class :


package {
    public class Singleton {
        private static var instance:Singleton;
        private static var allowInstance:Boolean ;
        public function Singleton() {
            if(!allowInstance) {
                 throw new Error("Error: use Singleton.getInstance() instead of new keyword");
            }
        }
        public static function getInstance():Singleton {
            if(instance  == null)
            {
                allowInstance = true;
                instance = new Singleton();
                allowInstance = false;
            }
            return instance;
       }
       public function doSomething():void {
           trace("doing something");
       }
    }
}


The preceding code uses a public method named getInstance to return a new instance of the Singleton class. Because it is called from within the class itself, the instantiation isn’t blocked by the private scope attribute of the class. Now, you might be wondering how we’ll be able to trigger that getInstance method, as we can’t create any new instance of the class to call it on. That’s where the static keyword comes in again. Any methods that are defined as static can be called by simply using the class name, in this case Singleton.getInstance().

var mySingleton:Singleton = Singleton.getInstance();
mySingleton.doSomething();

to see a singleton in a practical users manager example please download below source code ;

Source Code 
Online Demo

for any question please feel free to post it or mail me at abed_q@hotmail.com

Cheers.

No comments:

Post a Comment

Create facebook Iframe Application Using flash AS3 API ( Updated Version ).

please like and post your questions :  http://www.facebook.com/pages/FlashCS5-Tutorials/176320862386436 After I have received a lot of requ...