AS3.0 Better Singletons
I've found a better more robust way of enforcing singletons in AS3.0
Actionscript:
-
package
-
{
-
public class Singleton
-
{
-
public static var instance:Singleton;
-
-
public static function getInstance():Singleton
-
{
-
if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
-
return instance;
-
}
-
-
public function Singleton( pvt:SingletonEnforcer )
-
{
-
// init class
-
}
-
}
-
}
-
-
internal class SingletonEnforcer{}
Note: The class "SingletonEnforcer" is actually placed within the same .as file as the Singleton class, but placed outside the package{} parenthesis, therefore, the class "SingletonEnforcer" can only be accessed from within this .as file, so if the Singleton's constructor is called from anywhere else, you'll get an error.
7 Comments so far
Leave a reply
This is nice - I guess ECMA doesn't like private constructors? Any reason not to include the PrivateClass in the package?
Exactly, ECMA doesn't allow private constructors. The PrivateClass is outside the package so that i can only be accessed by code within the current .as file (if it was in the package{} I'd assume it would be accessible elsewhere within the package.
I discovered another implenentation by Daniel Hai on http://www.onflex.org/code/
The private static instance variable is instantiated on declaration. Simple and clean:
package
{
public class Singleton
{
private static var instance:Singleton = new Singleton();
public function Singleton()
{
if( instance ) throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
}
public static function getInstance():Singleton
{
return instance;
}
}
}
Thanks YOu Alll
Beatıfull one work, thank you
I Thınk Such Knowledge see The Interest.. thanks.!
Shouldn't it be:
public static var get instance():Singleton { return getInstance(); }
and change all the instance to _instance (to avoid the conflict)?