Last active
December 31, 2018 17:30
-
-
Save nfroidure/5676292 to your computer and use it in GitHub Desktop.
Part of my blog post Revisiting Singleton Design Pattern : https:///insertafter.com
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
// 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