Implement the Singleton In AS3

Implement the Singleton In AS3

The following example implement the Singleton In AS3 at the run-time.I don’t know if there is some other way to implement the Singleton in Compile-time.

 

From http://www.tink.ws/blog/stricter-singletons/

Strict Singletons in AS 3.0

With As 3.0 conforming to ECMA there you can no longer have private constructors which makes creating strict singletons a little bit more tricky. If I write a singleton, I want it written in a way that only a single instance can be created and if someone makes a mistake and tries to create an instance without using getInstance() an error will be thrown. This is a little workaround me and Rich came up with.

 

package
{
 
    public class Singleton
    {
        private static var instance:Singleton;
        private static var creatingSingleton:Boolean = false;
         
        public function Singleton()
        {
        if( !creatingSingleton ) throw new Error( “Singleton and can only be accessed through Singleton.getInstance()” );
        }
         
        public static function getInstance():Singleton
        {
         
            if( !instance )
            {
                creatingSingleton = true;
                instance = new Singleton();
                creatingSingleton = false;
            }
         
            return instance;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章