Here is the current implementation of the singleton pattern I use 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 { } |
