Thursday, June 17, 2010

Singleton in ActionScript!

This is how you'd go about creating a Singleton in ActionScript! Create another class within the same file but outside the package declaration - so that it can only be accessed internally:


package{
    public class Singleton{
        private static var _instance:Singleton=null;
        public function Singleton(e:SingletonEnforcer){
            trace(‘new instance of singleton created’);
        }
        public static function getInstance():Singleton{
            if(_instance==null){
                _instance=new Singleton(new SingletonEnforcer());
            }
            return _instance;
        }
    }
}
//I’m outside the package so I can only be accessed internally
class SingletonEnforcer{
//nothing else required here
}

No comments:

Post a Comment