Last active
April 25, 2016 16:37
-
-
Save pbse/8ba9adca5b2eaf8cfbc7f1cc1e3ae91d to your computer and use it in GitHub Desktop.
Singleton Pattern
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
| var Singleton = function() { | |
| // Check if there exists the first object | |
| if (typeof Singleton.instance === "object") { | |
| return Singleton.instance; | |
| } | |
| // Logger function. This could do anything. | |
| this.log = function(message) { | |
| console.log(message); | |
| } | |
| // We are Sure that below code will only execute if | |
| // this is the first time call. | |
| Singleton.instance = this; | |
| // Simply return the current Instance | |
| return this; | |
| } | |
| // Test Cases | |
| var single = new Singleton(); | |
| var single2 = new Singleton(); | |
| var single3 = Singleton(); | |
| // If the above 3 Objects point to only one Object, | |
| // We should get true if we check their equality. | |
| console.log(single === single2); | |
| // Logs true | |
| console.log(single2 === single3); | |
| // Logs true | |
| console.log(single === single3); | |
| // Logs true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment