Skip to content

Instantly share code, notes, and snippets.

@pbse
Last active April 25, 2016 16:37
Show Gist options
  • Select an option

  • Save pbse/8ba9adca5b2eaf8cfbc7f1cc1e3ae91d to your computer and use it in GitHub Desktop.

Select an option

Save pbse/8ba9adca5b2eaf8cfbc7f1cc1e3ae91d to your computer and use it in GitHub Desktop.
Singleton Pattern
var Singleton = function() {
// Check if there exists the first object
if (typeof Singleton.instance === "object") {
return Singleton.instance;
}
// Logger function. This could do anything.
this.log = function(message) {
console.log(message);
}
// We are Sure that below code will only execute if
// this is the first time call.
Singleton.instance = this;
// Simply return the current Instance
return this;
}
// Test Cases
var single = new Singleton();
var single2 = new Singleton();
var single3 = Singleton();
// If the above 3 Objects point to only one Object,
// We should get true if we check their equality.
console.log(single === single2);
// Logs true
console.log(single2 === single3);
// Logs true
console.log(single === single3);
// Logs true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment