使用es6 class 实现单例模式

// 创建一个单例模式类
class Singleton {
    constructor() {
        if(!Singleton.instance) {
            this.name = null
            Singleton.instance = this
        }
        return Singleton.instance
    }
    
    setName(name) {
        this.name = name
    }
    
    toString() {
        console.log(`This is Singleton toString, the name is ${this.name}.`)
    }
    
    static getInstance() {
        if (!this.instance) {
            return this.instance = new Singleton()
        }
        return this.instance
    }
}

let sing1 = Singleton.getInstance()
let sing2 = Singleton.getInstance()
let sing3 = new Singleton()
let sing4 = new Singleton()
// sing1 === sing2  true
// sing2 === sing3  true
// sing3 === sing4  true

你可能感兴趣的:(使用es6 class 实现单例模式)