Skip to content

Instantly share code, notes, and snippets.

@diurnalist
Created April 12, 2012 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diurnalist/2364744 to your computer and use it in GitHub Desktop.
Save diurnalist/2364744 to your computer and use it in GitHub Desktop.
Simple JS Multiton/Factory
var Multiton = (function() {
var _instances = {},
_products, _default;
function create_instance(name) {
var prefix = 'Product_',
product_name;
product_name = prefix + name.slice(0, 1).toUpperCase() + name.substring(1);
if (typeof _products[product_name] === 'function') {
return new _products[product_name]();
}
// warn user of invalid instantiation attempt
return null;
}
_products = {
Product_Concrete: function Product_Concrete() {
// product code
}
};
_default = 'concrete';
return {
instance: function(name) {
name = typeof name === 'string' || _default;
if (typeof _instances[name] === 'undefined') {
_instances[name] = create_instance(name);
}
return _instances[name];
}
};
})();​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment