- Restricts instance creation from the object
- Is useful when exactly one object is needed to coordinate others across a system
Last active
February 21, 2017 17:53
-
-
Save g-akshay/8beca0f7826363cf4f2e68d3b4311c29 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 mySingleton = (function () { | |
| // Instance stores a reference to the Singleton | |
| var instance; | |
| function init() { | |
| // Singleton | |
| // Private methods and variables | |
| function privateMethod(){ | |
| console.log( "I am private" ); | |
| } | |
| var privateVariable = "Im also private"; | |
| var privateRandomNumber = Math.random(); | |
| return { | |
| // Public methods and variables | |
| publicMethod: function () { | |
| console.log( "The public can see me!" ); | |
| }, | |
| publicProperty: "I am also public", | |
| getRandomNumber: function() { | |
| return privateRandomNumber; | |
| } | |
| }; | |
| } | |
| return { | |
| // Get the Singleton instance if one exists | |
| // or create one if it doesn't | |
| getInstance: function () { | |
| if ( !instance ) { | |
| instance = init(); | |
| } | |
| return instance; | |
| } | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment