js实现单例模式

187 阅读1分钟

人生到处知何似,恰似飞鸿踏雪泥。

如何使用js实现单例模式?简单实现如下:

class demo{
    constructor(obj){
        this.params = obj
    }
    static getInstance(obj){
        if(!this.instance){
            this.instance = new demo(obj)
        }
        return this.instance
    }
    add(key,val){
        this[key] = val
    }
}

使用如下:

let instance = demo.getInstance()
instance.add('name','小明')

单例变种:

class demo{
    constructor(obj){
        this.params = obj
    }
    static getInstance(key,obj){
        if(!this[key]){
            this[key] = new demo(obj)
        }
        return this[key]
    }
    add(key,val){
        this[key] = val
    }
}

使用如下:

let a = demo.getInstance('one')
let b = demo.getInstance('two')
a.add('name','小红')
let c = demo.getInstance('one')
console.log(c,b)

单例模式是较为常用的模式,于此稍作记录。