How to create a Singleton in Actionscript

package {
 
	public class MySingleton {
 
		private static var _instance:MySingleton;
 
 
		public function MySingleton(s:SingletonEnforcer) {
			if (s == null) throw new Error("Singleton, use MySingleton.instance");
		}
 
		public static function get instance():MySingleton {
			if (_instance == null) _instance = new MySingleton(new SingletonEnforcer());
			return _instance;
		}
	}
}
class SingletonEnforcer {}

Then use MySingleton.instance to retrieve the singleton instance.

Q: What does SingletonEnforcer do?
A: SingletonEnforcer is an inline class that only MySingleton can see, therefore, only MySingleton can construct itself.

*** Edit ***

Posted below is possibly a better way, as it doesn't require an inline class, although it may be less clear in this version that you shouldn't construct it normally as new MySingleton() won't give a compilation error:

package {
 
	public class MySingleton {
 
		private static var _instance:MySingleton;
		private static var _isConstructing:Boolean;
 
		public function MySingleton() {
			if (!_isConstructing) throw new Error("Singleton, use MySingleton.instance");
		}
 
		public static function get instance():MySingleton {
			if (_instance == null)  {
				_isConstructing = true;
				_instance = new MySingleton();
				_isConstructing = false;
			}
			return _instance;
		}
	}
}

Another way, without creating another class and instance of it (Singleton enfoncer) and easier IMO is to declare private static field (ie. access) and set it to FALSE as default.

package {

public class MySingleton {

private static var _access:Boolean = false;
private static var _instance:MySingleton;

public function MySingleton() {
if (!_access) { throw new Exception('Singleton'); }
}

public static function get instance():MySingleton {
if (_instance == null) {
_access = true;
_instance = new MySingleton();
_access = false;
}
return _instance;
}
}
}