Created
December 27, 2016 08:24
-
-
Save aelshamy/76041d345653fb9e07818eb0edbc7667 to your computer and use it in GitHub Desktop.
Singleton Design Pattern created by aelshamy - https://repl.it/ExOP/0
This file contains hidden or 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 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