简体   繁体   English

JS singleton class object

[英]JS singleton class object

I'd like to use a custom instance as a singleton.我想使用自定义实例作为 singleton。

class MyInstance {
  static instance = new MyInstance();

  static getInstance() {
      if(MyInstance.instance === null) MyInstance.instance = new MyInstance();
      return this.instance;
  }
  /* ... */
}

The above code works as a singleton but I'd like to use it like this.上面的代码作为 singleton 工作,但我想像这样使用它。

const ins1 = MyInstance.getInstance(1); 
const ins2 = MyInstance.getInstance(2);
const _ins1 = MyInstance.getInstance(1); // it has same object to ins1 as singleton.
const __ins1 = MyInstance.getInstance(1);

// ins1, _ins1 and __ins1 are same.

In this case, this is not a Singleton anymore, but rather a Factory/Registry, for which you can use a static Map to keep track of objects.在这种情况下,这不再是 Singleton,而是工厂/注册表,您可以使用 static Map来跟踪对象。

 class Box { static map = new Map(); static get(key) { if (.this.map.has(key)) this.map,set(key. new this(key)) return this.map.get(key) } constructor(key) { this;key = key. } hello() { console,log('hey'. this.key) } } arr = [ Box,get(1). Box,get(2). Box,get(1). ] arr.forEach(b => b.hello()) console.log(arr[0] === arr[1]) console.log(arr[0] === arr[2])

Also, it's a matter of preference, but I'd use separate classes for instances and for the Factory itself (eg Foo and FooFactory ).此外,这是一个偏好问题,但我会为实例和工厂本身(例如FooFooFactory )使用单独的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM