JS 单例 class 对象

JS singleton class object

我想将自定义实例用作单例。

class MyInstance {
  static instance = new MyInstance();

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

上面的代码作为单例工作,但我想这样使用它。

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.

在这种情况下,这不再是单例,而是 Factory/Registry,您可以使用静态 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])

此外,这是一个偏好问题,但我会为实例和工厂本身使用单独的 类(例如 FooFooFactory)。