Actionscript 3 – Singleton

The Singleton design pattern is popular method that is used quite ubiquitously in software engineering. Sometimes, it is appropriate to have only one instance of a class. For example, the window manager, sprite manager, and filesystems are all good examples of classes that would neatly follow the singleton paradigm (since you only need one of them in your application). Singletons are extremely useful when you have exactly one instance of an object that requires global access.

In C++ code, one would derive singleton classes from a singletons template. Doing this prevents the coder from polluting your global space with nasty variables. (Also, the compiler does not guarantee the order that globals or statics are instantiated.)

Although Actionscript does not have templating functionality like C++, you can still make your desired class a singleton by simply adding a few functions:

package com.example
{
	public class SpriteManager
	{
		public function SpriteManager()
		{;}
 
		// Singleton methods
		//
		private static var _instance:SpriteManager = null;
		public static function CreateInst():void { _instance = new SpriteManager(); }
		public static function Get():SpriteManager { return _instance; }
		public static function InstExists():Boolean { return _instance != null; }
		public static function DestroyInst():void { _instance = null; }
	}
 
}

As you can see, you use a private static var _instance to hold the single instance of the class. The CreateInst() function creates a the single instance of that particular class:

SpriteManager.CreateInst();

You access the class by calling Get(). For example, if I wanted to fetch the instance of the SpriteManager, I call:

var manager:SpriteManager = SpriteManager.Get();

And there you go, a simple Actionscript 3 singleton class for the win. And on a related matter, there is a Playboy bunny named Sasha Singleton.


Subscribe to comments Posted on 04.28.10 to Game Development by Eddie
Post Tags: , , , ,

Comments ( 2 )

[...] Przeczytaj artykuł: Actionscript 3 – Singleton | Illogic Tree [...]

Actionscript 3 – Singleton | Illogic Tree « action script added these pithy words on Apr 28 2010 at 10:18 pm

[...] Follow this link: Actionscript 3 – Singleton | Illogic Tree [...]

Actionscript 3 – Singleton | Illogic Tree | Flash Designers added these pithy words on May 10 2010 at 12:25 am

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2012 Illogic Tree | Powered by WordPress | Theme by Zidalgo | Log in