Created
June 3, 2011 10:57
-
-
Save oslego/1006177 to your computer and use it in GitHub Desktop.
JavaScript Multiton Example
This file contains hidden or 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
| /* | |
| Use, reuse but don't abuse! | |
| Author: Razvan Caliman (razvan.caliman@gmail.com) | |
| This is an example of a "Multiton" pattern; | |
| Create a fixed number of instances of a class. | |
| Use "lazy instantiation" to create objects only if needed. | |
| If the maximum number of instances has been reached, return a random one from the ones created. | |
| */ | |
| var Multiton = (function () { | |
| var inst = [], | |
| maxInst = 4; | |
| var Multiton = function () { | |
| this.inst = inst; | |
| }; | |
| return function () { | |
| var p, rand; | |
| //Still room for instances, create | |
| if (inst.length < maxInst){ | |
| p = new Multiton(); | |
| inst.push(p); | |
| } | |
| //Enough instances, return a random one | |
| else{ | |
| rand = Math.floor(Math.random()*4); | |
| p = inst[rand]; | |
| console.log("Max instances reached, you get instance: "+rand, p); | |
| } | |
| return p; | |
| } | |
| })(); | |
| var p1 = new Multiton() | |
| var p2 = new Multiton() | |
| var p3 = new Multiton() | |
| var p4 = new Multiton() | |
| var p5 = new Multiton() | |
| console.log(p1,p2,p3,p4,p5); |
Would this not still create garbage objects since the lambda being returned by the outer Multiton object is being instantiated by the new operator in lines 38-42, regardless of what is being returned?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey! Thanks for the example. This is a great, great example! For a minute I was baffled about the private scope constructor inside of the primary self-invoking constructor - really cool to see that in action. It's interesting that JavaScript will use the Multiton declaration in the nearest scope versus the one in global scope.
I also think I found a typo in your else clause where you are doing Math.random() * 4, and it should be Math.random() * maxInst
Thanks for the example!