function CreatePerson(name) {
this.name = name;
}
const CreateSinglePerson = (function () {
let instance;
return {
create(name) {
if (!instance) {
instance = new CreatePerson(name);
}
return instance;
},
};
})();
let person1 = new CreatePerson("messi");
let person2 = new CreatePerson("ronaldo");
console.log(person1 === person2);
// false
person1 = CreateSinglePerson.create("messi");
person2 = CreateSinglePerson.create("ronaldo");
console.log(person1.name);
// messi
console.log(person2.name);
// messi
console.log(person1 === person2);
// true
Singleton Pattern
Using ES5 syntax
class CreatePerson {
constructor(name) {
this.name = name;
}
}
class CreateSinglePerson {
static instance;
constructor(name) {
if (!CreateSinglePerson.instance) {
CreateSinglePerson.instance = new CreatePerson(name);
}
return CreateSinglePerson.instance;
}
}
let person1 = new CreatePerson("messi");
let person2 = new CreatePerson("ronaldo");
console.log(person1 === person2);
// false
person1 = new CreateSinglePerson("messi");
person2 = new CreateSinglePerson("ronaldo");
console.log(person1.name);
// messi
console.log(person2.name);
// messi
console.log(person1 === person2);
// true