Categories
ActionScript Design Patterns OOP Tips & Tricks

Singleton

Here’s one way to implement a Singleton in ActionScript 2.0:

class Singleton {
    // the only instance of this class
    private static var inst:Singleton;

    // keep count of the number of Singleton objects referenced
    private static var refCount:Number = 0;

    // constructor is private
    private function Singleton() {}

    // get an instance of the class
    public static function get instance():Singleton {
        if (inst == null) inst = new Singleton();
        ++refCount;
        return inst;
    }

    // return the number of instance references
    public static function get referenceCount():Number {
        return refCount;
    }
}


The count property is for keeping count of the number of Singleton objects referenced (obviously it is not aware of destroyed objects), and is not really a necessary member of the Singleton pattern.

To use this class, one would write something like this:

var s1:Singleton = Singleton.instance;
var s2:Singleton = Singleton.instance;

Now s1 and s2 are the same instance of the Singleton class.

5 replies on “Singleton”

I use Singeltons all the time. One minor pick with your code/comments:

The instanceCount is really a reference count since a Singleton only ever has one instance by definition. Could be confusing to people new to Singletons.

Great blog!

Do you have any opinions on Singletons versus Static Classes?

(With Static Classes i mean like the Built in Math class and som of the mx.managers classes.) I understand both Singletons and static classes, I’m just not sure when to use what.

To complicate things a bit further there is also the mx.events.EventDispacher that act as a static class but internally uses the Singleton Pattern in its initialize method.

static function initialize(object:Object):Void
{
if (_fEventDispatcher == undefined)
{
_fEventDispatcher = new EventDispatcher;
}
object.addEventListener = _fEventDispatcher.addEventListener;
object.removeEventListener = _fEventDispatcher.removeEventListener;
object.dispatchEvent = _fEventDispatcher.dispatchEvent;
object.dispatchQueue = _fEventDispatcher.dispatchQueue;
}

Static Classes (e.g. Math) have no state, meaning they don’t keep track of anything (they don’t have any member variables), they are functions to perform work (e.g. math operations) and forget everything after they are done.

Singletons however do keep track of things, but there should only be one of these states across the entire application, e.g. in an application involving banks you should only have one instance of a users checking account, so any operations performed (adding/removing money) across different sections (e.g. add deposit, pay bills) keep everything in synch.

Leave a Reply

Your email address will not be published. Required fields are marked *