Singleton

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


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 thoughts on “Singleton

  1. 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!

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

  3. Great AS 2.0 implementation of the Singleton pattern Dave, have you got a practical example where you would use that static count property?

  4. 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 *

+ 2 = twelve