Is there any difference between the following approaches? I am fond of the second approach as it is more clear but I am seeing Approach 1 also on the internet. So wondering if there any benefit of one approach over other.
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()
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()
Second one is preferable I think. First one actually allows instantiating multiple times.