最简单的单例模式
class Window { constructor(name) { this.name = name; } static getInstance() { // 静态方法 this是Window类 // 第一次走new window方法 ,第二次this.instance就有值,用自己的 this.instance = this.instance || new Window return this.instance } } const w1 = Window.getInstance() const w2 = Window.getInstance() console.log(w1 === w2); //true
两个缺点:
1.调用者必须知道Window类有getInstance静态方法。
2.不能阻止调用者new Window().这样会产出多个实例对象。
透明单例
class Window { constructor(name) { this.name = name; } getName() { console.log(this.name); } } const CreateSingleton = (function () { let instance = null return function CreateSingleton(name) { instance = instance || new Window(name) return instance } })() const w1 = new CreateSingleton('w1') //new 可以不用 const w2 = new CreateSingleton('w2') console.log(w1 === w2); //true
扩展透明单例:如果有多个类,而创建单例的逻辑是一样的。
class Window { constructor(name) { this.name = name; } getName() { console.log(this.name); } } class Dialog { constructor(title, content) { this.title = title; this.content = content; } } const CreateSingleton = function (Constructor) { let instance = null return function (...args) { instance = instance || new Constructor(...args) return instance } } // 创建Window单例 const CreateWindow = CreateSingleton(Window) //创建Window单例 const w1 = new CreateWindow('w1') //new 可以不用 const w2 = new CreateWindow('w2') // 创建Dialog单例 const CreateDialog = CreateSingleton(Dialog) const d1 = new CreateDialog('t1', 'c1') const d2 = new CreateDialog('t2', 'c2') console.log(d1); //Dialog { title: 't1', content: 'c1' } console.log(d2); //Dialog { title: 't1', content: 'c1' }