Created
August 22, 2011 23:53
-
-
Save dsimard/1163955 to your computer and use it in GitHub Desktop.
Javascript singleton
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 Cats() { | |
| var names = []; | |
| // Get the instance of the Cats class | |
| // If there's none, instanciate one | |
| var getInstance = function() { | |
| if (!Cats.singletonInstance) { | |
| Cats.singletonInstance = createInstance(); | |
| } | |
| return Cats.singletonInstance; | |
| } | |
| // Create an instance of the Cats class | |
| var createInstance = function() { | |
| // Here, you return all public methods and variables | |
| return { | |
| add : function(name) { | |
| names.push(name); | |
| return this.names(); | |
| }, | |
| names : function() { | |
| return names; | |
| } | |
| } | |
| } | |
| return getInstance(); | |
| } |
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 run() { | |
| // Add a new cat | |
| var cat1 = new Cats(); | |
| cat1.add("Mistigri"); | |
| console.log("cat1 contains 1 cat : " + cat1.names().toString()); | |
| // Use another instance | |
| var cat2 = new Cats(); | |
| console.log("cat2 contains Mistigri added in cat1 : " + cat2.names().toString()); | |
| // Add another cat in the other instance | |
| cat2.add("Felix"); | |
| console.log("cat2 contains Mistigri and Felix : " + cat2.names().toString()); | |
| console.log("cat1 also contains Mistigri and Felix : " + cat1.names().toString()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment