• Implementing Singleton in ActionScript 3.0

    by  • December 16, 2011 • Tutorials

    Singleton is one of the simplest and very useful design pattern we run across very often.

    In object-oriented programming , a singleton class is a class that can have only one object (an instance of the class) at a time.

    ActionScript 3.0 doesn’t allow private constructor functions, so you can’t directly create a Singleton class. But there are a way around to have singleton functionality in ActionScript 3.0 as well. I call it the locksmith approach.

    The concept is you can only create the class if you have the key to the lock, and no one outside the class has the key so no one can create the class 🙂 Lets get into the code to see how it works.

    package  {
    
    	public class Singleton {
    
    		private static var m_oInstance:Singleton;
    
    		public function Singleton(SingletonKey:Class) {
    			// constructor code
    			if(SingletonKey==SingletonLock) {
    				Singleton.m_oInstance = this;
    			}else {
    				throw new Error("Invalid Singleton access. Use Singleton.getInstance().");
    			}
    		}
    
    		public static function getInstance():Singleton {
    			if(m_oInstance==null) {
    				Singleton.m_oInstance = new Singleton(SingletonLock);
    			}
    			return Singleton.m_oInstance;
    		}
    
    	}
    
    }
    class SingletonLock{
    
    }

    Lets examine the code snippet…

    Line 26-28 This is our lock, this is a class defined inside our Singleton class that can not be created from outside.

    Line 16-21 This is the function makes sure at any instance of time there are only one instance of our singleton class. It checks weather the class has been instantiated before or not. If not it creates the instance and return it or it returns the existing instance of the class. The outside world can only get access to the singleton class through this function getInstance().

    Line 7-14 The constructor, it expects the key to the lock. It compares the key provided with the lock, and if it is a match it creates an instance of our Singleton class. If the key doesn’t match with the lock it throws and Error and  even at the compile time we know someone is trying to directly create our singleton class.

    This is how you implement a singleton class in ActioScript 3.0. In my next blog I will discuss Factory design pattern.

     

    About

    An accomplished Game Developer with 4 years’ experience covering all aspects of the game development life-cycle including designing, development, testing and maintenance. Have extensive experience in flash based web, desktop and mobile games and other rich internet applications like small websites, software prototypes, portfolios and many more.

    https://plus.google.com/117140375336587355364