【问题标题】:Exporting the object of the class vs exporting the singleton class. Javascript导出类的对象与导出单例类。 Javascript
【发布时间】:2021-11-19 06:05:28
【问题描述】:

以下方法有什么区别吗?我喜欢第二种方法,因为它更清晰,但我也在互联网上看到方法 1。所以想知道一种方法是否比其他方法有任何好处。

方法 1

Singleton.ts

class Singleton {
    private static _instance: Singleton | null = null
    
    private constructor() {}
    
    public static getInstance() {
        if (!Singleton._instance) {
            Singleton._instance = new Singleton()
        }
        return Singleton._instance
    }
    
    public doSomeWork() {}
}


export default Singleton

test1.ts

import Singleton from './Singleton'

Singleton.getInstance().doSomeWork()

test2.ts

import Singleton from './Singleton'

Singleton.getInstance().doSomeWork()

方法2

Singleton.ts

class Singleton {
    constructor() {
        
    }    
    
    public doSomeWork() {}
}


export default new Singleton()

test1.ts

import singleton from './Singleton'

singleton.doSomeWork()

test2.ts

import singleton from './Singleton'

singleton.doSomeWork()

【问题讨论】:

    标签: javascript singleton


    【解决方案1】:

    我认为第二个更好。第一个实际上允许实例化多次。

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多