Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Last active December 31, 2018 17:30
Show Gist options
  • Save nfroidure/5676292 to your computer and use it in GitHub Desktop.
Save nfroidure/5676292 to your computer and use it in GitHub Desktop.
Part of my blog post Revisiting Singleton Design Pattern : https:///insertafter.com
// Singleton pattern
var MySingleton=(function() {
// creating a variable to contain the instance
var instance=null;
// here goes private stuff
var _myPrivateVar=1;
var _myPrivateFunction=function(){
console.log('In private function.');
};
// creating singleton constructor
function Constructor() {
// assigning instance to our variable
instance=this;
}
// here goes public method and properties
Constructor.prototype.publicProperty=1;
Constructor.prototype.publicMethod=function() {
console.log('In public method.');
_myPrivateFunction();
};
// creating a constructor to generate an exception
var FakeContructor=function() {
throw SyntaxError('Singleton : Use getInstance instead.');
}
// associating him getInstance()
FakeContructor.getInstance=function(){
return instance || new Constructor();
};
return FakeContructor;
})();
// Usage
var singleton=MySingleton.getInstance();
console.log(singleton===MySingleton.getInstance()
&&singleton===MySingleton.getInstance()
&&singleton===MySingleton.getInstance());
// true
console.log(singleton.publicProperty);
// 1
singleton.publicMethod();
// In public method.
// In private function.
// Misuse attempts
var singleton=new MySingleton();
// SyntaxError : Singleton : Use getInstance instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment