簡體   English   中英

JS singleton class object

[英]JS singleton class object

我想使用自定義實例作為 singleton。

class MyInstance {
  static instance = new MyInstance();

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

上面的代碼作為 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.

在這種情況下,這不再是 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])

此外,這是一個偏好問題,但我會為實例和工廠本身(例如FooFooFactory )使用單獨的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM