The AS3 Singleton Revisited

Originally posted 29NOV07 on onebyonedesign.com.

It seems since the release of AS3, there has been much public debate on how to construct a good Singleton. For those wondering, the Singleton is a design pattern which allows for only a single instantiation of a particular class to take place. This is particularly useful for manager objects or for other items you may only want one of at any given time (tooltips, media players, etc.). In most languages, the Singleton is created using a private constructor method accessed by a static method of the Singleton class. Ecmascript (and hence Actionscript 3) does not allow for private constructors, however, so other ingenious methods have been devised for simulating such a thing. The most common one is to create a second class in the same .as file as the Singleton class and passing an instance within the Singleton’s constructor. Because of the way actionscript operates, any additional classes in one .as file can only be accessed by the main class in that file. They are then, in essence, private classes. There have been some arguments against this method though – the biggest being that having two classes in the same file is a bit of a design faux pas. This then is my take on the subject. I decided to go with the little used arguments array to pass a reference to the calling function to the Singleton’s constructor to guarantee only a single instance. A quick example:

/** 
* Singleton example using arguments.callee 
* property to enforce single instantiation. 
* @author Devon O. 
*/  
 
package {  
 
	public class Singleton {  
 
		private static var _thisInstance:Singleton;  
 
		public function Singleton(caller:Function) { 
			if (!(caller == makeInstance)) { 
				// throw error 
			} else { 
				// instantiate it up 
			} 
		}  
 
		public static function getInstance():Singleton { 
			if (!_thisInstance) 
				_thisInstance = Singleton.makeInstance(); 
			return _thisInstance; 
		}  
 
		private static function makeInstance():Singleton { 
			return new Singleton(arguments.callee); 
		} 
	} 
}

To use it, you simply create your object with:

var mySingleton:Singleton = Singleton.getInstance();

Unfortunately this approach calls for an additional private method (makeInstance()) to get the job done, but it at least requires only a single class rather than using a private “helper” class.

1 Comment

  1. Nuno R. says:

    Hi, Devon.
    I’ve also read a couple of post on how to implement it, don’t even implement it, etc.

    And i must say… i really like the way you’ve done it.

    PS: Glad to see you start blogging and hopefully your “preloader” will finish soon. :)

TrackBack URI

Sorry, the comment form is closed at this time.

Devon O. Wolfgang

Technical Reviewer of “The Essential Guide to Flash CS4 AIR Development”

Contributing Author of “Flash AS3 for Interactive Agencies”

Senior Software Developer in Dublin, Ireland

Portfolio

Bayer Pixel Bender Filter

Bayer Mosaic Filter in Pixel Bender


Now, seeing as how I’ve been trying to learn some Pixel Bender coding lately[...]

Liquitext

Liquid Text Effect


Haven’t been too active around here lately due to a major on going project at work lately as well as the fact that my wife and I are in the slow process of moving homes. Really, the only free time it seems I have these days is during the lunch hour. So, over the past two days, I came up with this fun little toy during lunches[...]

Google’s Text To Speech Engine in Flash

I’m not sure how I managed to miss this, but I just happened to run across a ‘new’ (well, newish), albeit still unofficial, offering of Google today: text-to-speech. You can see what few details there are on this Techcrunch post. Basically, it just boils down to this though – you send your phrase to be [...]

Quick Sound Effects Generator


Need some beeps, boops, or bops, to go with your UI or games [...]

Quick QuickBox2D Tip II – Collision Detection

Custom collision detection/handling in QuickBox2D [...]

None of This Runs Eternal


No Flash/Actionscript stuff here. Just me rambling about the upcoming Current 93 concert [...]

Playing Around with the New UndoManager

Included in the Flex 4.0 SDK and the, just released, Flash Professional CS5 lies a new hidden little gem of a class: flashx.undo.UndoManager (although the Flex 4.0 SDK’s been out for awhile, I have to admit I didn’t even notice this until I installed Flash CS5 and started poking around the documentation looking for new [...]

Making Waves

In a previous post, “Digging into the Microphone in Flash Player 10.1″, reader David Law asked in the comments how it would be possible to save .wav files to the server. I wasn’t sure right offhand, but thought I’d spend my lunch hour yesterday looking into it. Well, after reading this quick tutorial on Adobe [...]

Some Drawing Fun and a Bad Movie You’ll Never See

Earlier today, Dave Gillem posted a link on Facebook to an incredible Processing based drawing application. Thought I’d have a go at reproducing something similar in Flash. Well, I failed miserably, but the results were still interesting enough to check out. You can play around with it below. Just mouse down to draw in the [...]

Animating Bezier Curves


The other day I got the notion in my head that I wanted to draw some bezier curves in an animated fashion. I’m sure this has been done a million times before, but sometimes reinventing the wheel can be a good learning experience [...]

My God, It’s Full of Stars…


Just a quick little thing I got an idea for (i.e. pretty much ripped off) while browsing Processing examples.

Another Year, Another Look

As a few folks may have noticed, the blog is looking a little bit different as of today [...]

The Webcam Warholizer


Just a little bit of quick Friday fun with webcam and bitmapata…

More With the JiglibFlash Terrain

Playing around a bit more with the animated JiglibFlash terrain idea from my last post, I wanted to see how it would work in conjunction with a webcam. So, needless to say, you’ll need a webcam to check out the results below.

Rockin and Rollin with the JiglibFlash Terrain


Finally got the chance to play around with the new JiglibFlash height map terrain, today, and have to say I am very impressed [...]