singleton class in Flex

孤街醉人 提交于 2019-12-24 11:22:07

问题


I know singleton class is not supporting in Flex.Because it does not access private constructor.

But i want to make a class is singleton class. Please anyone can explain with example.

Thanks, Ravi


回答1:


A singleton is a class of which only one instance will be created. This instance will be shared by all other code in the program.

A singleton in the strictest sense is not supported in ActionScript because a constructor cannot be marked private. Consequently, additional instances of the class could be created elsewhere in the program. With the following trick, you can ensure that the constructor is only called by the singleton class itself:

package {

public final class Singleton {

    private static var instance:Singleton = new Singleton();

    public function Singleton() {
        if( Singleton.instance ) {
            throw new Error( 
                "Singleton and can only be accessed through Singleton.getInstance()" ); 
        }
    }

    public static function getInstance():Singleton {                        
        return Singleton.instance;
    }
}
}


来源:https://stackoverflow.com/questions/2217152/singleton-class-in-flex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!