So I've got a Singleton "class" that works pretty well:
function Base_Singleton () {
if ( Base_Singleton.prototype._singletonInstance )
return Base_Singleton.prototype._singletonInstance;
else
return Base_Singleton.prototype._singletonInstance = this;
}
This works great. You make multiple instances if you want, and they all reflect the changes of each other:
var sing1 = new Base_Singleton();
var sing2 = new Base_Singleton();
sing1.foo = "bar";
sing2.foo === "bar"; // true
So what I want now is to be able to create multiple Singleton interfaces, with their own info. I'm open to any way of accomplishing this. The two methods that came to mind were either extending or making a factory.
When I try extending, the new object just gets the prototype of the Base_Singleton
, so it's not extending anything it's just creating another instance.
I figure the best way is via a Factory that can create a new object each time:
var Singleton_Factory = new function () {
// Let's just assume this is in a web environment
var global = global || window;
/**
* Build a new object with Singleton functionality.
* Singleton functionality based from https://goo.gl/YfmiTH
*
* The idea is that there is an instance of the object shared through the
* singleton's prototype. You can create as many 'new' Singletons as you
* desire, but they all will mirror the same prototypical object.
*
* @param {string} singletonName The name of the new Singleton, and its
* prototype
* @param {object} namespace The namespace to add the new object to
*
* @return {object} The newly created Singleton
*/
this.make = function ( singletonName, namespace ) {
// Default to global object as defined earlier
namespace = namespace || global;
// If there is a shared _singletonInstance, return that
if ( namespace[singletonName].prototype._singletonInstance )
return namespace[singletonName].prototype._singletonInstance;
// If there isn't one, create and return 'this'
else
return namespace[singletonName].prototype._singletonInstance = this;
}
}
Problem here is that I'm trying to use prototype
on undefined.
How can I create a factory that can create a new prototype with the functionality of Base_Singleton
?