简体   繁体   中英

JS singleton class object

I'd like to use a custom instance as a 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.

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.

 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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