Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement a singleton pattern class in Actionscript 3?

Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.

I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.

The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?

like image 495
tronster Avatar asked Dec 05 '22 07:12

tronster


1 Answers

A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).

package {
    public class Singleton {

    private static var _instance:Singleton;

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

    public static function get instance():Singleton
    {
        if(!Singleton._instance)
        {
            Singleton._instance = new Singleton(new SingletonEnforcer());
        }

        return Singleton._instance;
    }
}

}
class SingletonEnforcer{}
like image 120
Iain Avatar answered Dec 09 '22 13:12

Iain