Created
June 6, 2009 07:52
-
-
Save sidonath/124766 to your computer and use it in GitHub Desktop.
Another take on singleton pattern in JavaScript
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
| function singleton(self, wrapper, ctor) { | |
| // support for early failing | |
| if (self instanceof wrapper) { | |
| throw wrapper.name + " " + | |
| "is a singleton, you cannot create its instance. " + | |
| "To get the isntance: " + wrapper.name + "();"; | |
| } | |
| if (!ctor) { | |
| return; | |
| } | |
| if (!wrapper.instance) { | |
| wrapper.instance = new ctor(); | |
| } | |
| return wrapper.instance; | |
| } | |
| function Hello() { | |
| // fail early if called with new Hello() <- not mandatory | |
| singleton(this, Hello); | |
| function HelloCtor() { | |
| this.id = String(Math.random()).replace("0.", ''); | |
| this.hi = function() { alert("Hello, World! " + this.id); }; | |
| alert("Constructing: " + this.id); | |
| } | |
| // construct the instance or return constructed | |
| return singleton(this, Hello, HelloCtor); | |
| } | |
| // constructor should be called only once and id should be the same | |
| Hello().hi(); | |
| Hello().hi(); | |
| // exception should be raised for new Hello() | |
| var caught = false; | |
| try { | |
| (new Hello()).hi(); | |
| } catch (ex) { | |
| alert("Exception caught: " + ex); | |
| caught = true; | |
| } | |
| if (!caught) { | |
| alert("Exception not caught when creating singleton") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment