Created
April 12, 2012 05:14
-
-
Save diurnalist/2364744 to your computer and use it in GitHub Desktop.
Simple JS Multiton/Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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