【每日一个成长小技巧】前端单例模式

TS写法

//单例模式
class Demo {
    private static instance: Demo;
    private constructor(public name:string){

    }
    static getInstance(name:string){
        if(!this.instance){
            this.instance = new Demo(name)
        }
        return this.instance
        
    }
}

const demo1 = Demo.getInstance("zhangsan");
const demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true

ES6写法

//es6
class Demo{
    constructor(name){
        this.instance = null;
        this.name = name;
    }

    static getInstance(name){
        if(!this.instance){
            this.instance = new Demo(name)
        }
        return this.instance
    }
}

const demo1 = Demo.getInstance("zhangsan");
const demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true

ES5写法

//es5
function Demo(name){
    this.name = name;
    this.instance = null
}
Demo.getInstance = function(name){
    if(!this.instance){
        this.instance = new Demo(name)
    }
    return this.instance;
   
}

var demo1 = Demo.getInstance("zhangsan");
var demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true
上一篇:设计模式之单例模式C++实现


下一篇:设计模式。单例-》饿汉式