Joe's Blog

line

A blog by Joe Billman about programming, and other stuff

line

Archive for February, 2014

AS3 Singleton

Posted on: February 7th, 2014 by Joe

line No Comments

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;
	}

}

 


Warning: Use of undefined constant Y - assumed 'Y' (this will throw an Error in a future version of PHP) in /homepages/16/d145171736/htdocs/php/footer.php on line 1