-
-
Save jasonwyatt/1106973 to your computer and use it in GitHub Desktop.
define(function(){ | |
var instance = null; | |
function MySingleton(){ | |
if(instance !== null){ | |
throw new Error("Cannot instantiate more than one MySingleton, use MySingleton.getInstance()"); | |
} | |
this.initialize(); | |
} | |
MySingleton.prototype = { | |
initialize: function(){ | |
// summary: | |
// Initializes the singleton. | |
this.foo = 0; | |
this.bar = 1; | |
} | |
}; | |
MySingleton.getInstance = function(){ | |
// summary: | |
// Gets an instance of the singleton. It is better to use | |
if(instance === null){ | |
instance = new MySingleton(); | |
} | |
return instance; | |
}; | |
return MySingleton.getInstance(); | |
}); |
pretty interesting @jt000!!
@jt000 but that's not a singleton. The concept of a singleton is that you can't make individual instances of it. Or am I missing something from your example? All you're doing there is making a second require that I have to import to provide the illusion of a singleton.
Imagine doing that for 50 classes in a project. You all of a sudden have 100 defines...
@jasonwyatt Out of curiosity, is there a reason that getInstance is even necessary? Why can't we just have the constructor point to _instance and return that if it's not null? I.e., here is my revised version that seems to return the same object every time. Note that it makes use of the fact that you can use a constructor to return anything you want.
define(function(require, exports, module)){
var _instance = null;
function MySingleton() {
//You can retrofit this to support calling init() where necessary... just keeping it brief :)
_instance = _instance === null ? this : _instance;
return _instance;
}
module.exports = MySingleton;
});
Seems to work for me... any reason you think this wouldn't be equivalent output-wise to yours? The upside to this is that it conforms more to the requirejs ecosystem and is easier to read.
Singletons are actually very easy using require. Just return the instance in your define. Personally, I like to go with this pattern: http://jsfiddle.net/jaytre/xLj1uw3r/
@herebebeasties - Require handles the laziness. The singleton won't be created until the first time
require(['mySingleton'], ...)
is called.