Skip to content

Instantly share code, notes, and snippets.

@robsta
Created May 18, 2009 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robsta/113390 to your computer and use it in GitHub Desktop.
Save robsta/113390 to your computer and use it in GitHub Desktop.
Singleton Pattern in Actionscript 3.0
package {
public final class Singleton {
/**
* Storage for the singleton instance.
*/
public static const instance:Singleton = new Singleton ( SingletonLock );
/**
* Constructor
*
* @param lock The Singleton lock class to pevent outside instantiation.
*/
public function Singleton(lock:Class) {
// Verify that the lock is the correct class reference.
if ( lock != SingletonLock ) {
throw new Error( "Invalid Singleton access. Use Singleton.instance." );
}
}
public static function getInstance():Singleton {
return Singleton.instance;
}
}
}
/**
* This is a private class declared outside of the package
* that is only accessible to classes inside of the Singleton.as
* file. Because of that, no outside code is able to get a
* reference to this class to pass to the constructor, which
* enables us to prevent outside instantiation.
*/
internal class SingletonLock { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment