我有以下代码来实现单例
const singleton = Symbol();
const singletonEnforcer = Symbol()
class SingletonTest {
constructor(enforcer) {
if(enforcer != singletonEnforcer) throw "Cannot construct singleton";
}
static get instance() {
if(!this[singleton]) {
this[singleton] = new SingletonTest(singletonEnforcer);
}
return this[singleton];
}
}
export default SingletonTest
和
import SingletonTest from 'singleton-test';
const instance = SingletonTest.instance;
我遇到竞争条件问题,当SingletonTest.instance
同时执行两次时,我有两个SingletonTest
实例,我该如何解决问题?