单例模式只能创建一个实例
function Person(name) {
this.name = name;
}
const p1 = new Person('qwe');
const p2 = new Person('asd');
console.log(p1 === p2);//false
//p1和p2是两个不同的实例,如果每次都只想创建同一个实例,则可以使用单例模式
单例模式核心代码
function Person(name) {
this.name = name;
}
let instance = null;
function singleTon(name) {
if(!instance){
instance = new Person(name);
}
return instance;
}
const p1 = singleTon('tyh');
const p2 = singleTon('xyr');
console.log(p1,p2);//p1和p2都是name='tyh'的实例
console.log(p1 === p2);//true
通过闭包的方式将整个单例模式实现
const Person = (function(){
function Person(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype.say = function() {
console.log("hello");
}
let instance = null;
return function singleTon(...arg){
if(!instance) instance = new Person(...arg);
return instance;
}
}());
const p1 = new Person('tyh',12,'男');
const p2 = new Person('xys',15,'女');
console.log(p1,p2);
console.log(p1 === p2);//true