AS3 Singleton

Singleton classes are very useful. So I wanted to show a simple sample of a Singleton class. I like to use these as models to store data in one location that multiple parts of your application can access. Singleton classes in ActionScript 3 for the most part are just like they are in other OOP languages. There is one minor difference. Since you can’t make a constructor private you have to add a few lines of code in the constructor. Here is a sample:

public class Singleton
{

	private static var _instance:Singleton = new Singleton();

	public function Singleton()
	{
		if(_instance != null)
		{
			throw new Error("Instantiation failed");
		}
	}

	public static function getInstance():Singleton
	{
		return _instance;
	}

}

That is my preferred way to do it for models that you know are going to be instantiated. Then you just add public variables and you have a model. Generally when I’m using models I always plan to instantiate them, but if you are not sure if you are going to instantiate the class you may want to do it like this:

public class Singleton
{

	private static var _instance:Singleton;

	public function Singleton()
	{
		if(_instance != null)
		{
			throw new Error("Instantiation failed");
		}
	}

	public static function getInstance():Singleton
	{
		if(_instance == null)
		{
			_instance = new Singleton();
		}
		return _instance;
	}

}