-
-
Save carldanley/6ac14bb0766e8bd146c5 to your computer and use it in GitHub Desktop.
Example of the Singleton pattern
This file contains 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( window, undefined ) { | |
var instance = null; | |
// revealing module pattern that handles initialization of our new module | |
function initializeNewModule() { | |
function myMethod() { | |
alert( 'my method' ); | |
} | |
function myOtherMethod() { | |
alert( 'my other method' ); | |
} | |
return { | |
someMethod : myMethod, | |
someOtherMethod : myOtherMethod | |
}; | |
} | |
// handles the prevention of additional instantiations | |
function getInstance() { | |
if( ! instance ) { | |
instance = new initializeNewModule(); | |
} | |
return instance; | |
} | |
return { | |
getInstance : getInstance | |
}; | |
} )( window ); | |
// example usage | |
mySingleton.getInstance().someMethod(); // alerts "my method" | |
mySingleton.getInstance().someOtherMethod(); // alerts "my other method" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment