Friday, March 11, 2011

Singleton Pattern in Dojo

Recently, I needed to have a singleton object. So, I came up with the following implementation to give me just that.
var makeSingleton = function (aClass) {
    aClass.singleton = function () {
        var localScope = arguments.callee;
        localScope.instance = localScope.instance || new aClass();
        return localScope.instance;
    };
    return aClass;
};

When declaring my class in Dojo, I did the following:
makeSingleton(dojo.declare(...));
Then, to use it:
var instance = myClass.singleton();
I like the fact with this implementation that it's obvious that I'm creating a singleton object up front around the dojo.declare. Of course, there's nothing preventing someone from creating the class with new, but we could easily get around that with throwing an exception in our constructor after our singleton has been initialized.

1 comment:

Wagner said...

thanks for sharing...