Skip to content

Instantly share code, notes, and snippets.

@aelshamy
Created December 27, 2016 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aelshamy/76041d345653fb9e07818eb0edbc7667 to your computer and use it in GitHub Desktop.
Save aelshamy/76041d345653fb9e07818eb0edbc7667 to your computer and use it in GitHub Desktop.
Singleton Design Pattern created by aelshamy - https://repl.it/ExOP/0
// Singleton design pattern ES5
var Singleton = (function(){
var instant;
function createInstant(){
var object = new Object("Iam instant");
return object;
}
return {
getInstant:function(){
if(!instant){
instant = createInstant();
}
return instant;
}
}
}());
var x1 = Singleton.getInstant();
var x2 = Singleton.getInstant();
console.log(x1 == x2);
// Singleton design pattern ES6
class UserObject{
constractor(){
if(!UserObject.instant){
this._data = [];
UserObject.instance = this;
}
return UserObject.instance;
}
add(item){
this._data.push(item);
}
get(id){
return this._data.find(d => d.id === id);
}
}
const instant = new UserObject();
Object.freeze(instant);
//export default UserObject;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment