views:

148

answers:

2

Hi,

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

+5  A: 

See the discussion here

Patrick
@Patrick: not cleared in that discussion link.
Ravi K Chowdary
What are you not understanding ?
Patrick
+2  A: 

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;
    }
}
}
Ravi K Chowdary