简体   繁体   中英

WeakMap Pattern Singleton without memory leak

class Cat {

  storage = new Map()  

  constructor(id) {
    if(storage.has(id)) return storage.get(id)
    storage.set(id, this)
  }

}

I want the object to be removed from the storage if references to it are not used in the application. But if the links in the application are exists, and we are trying to create an object with the same ID, then return this object, rather than create a new one. How i can do it without destructors?

But when all the references to the object disappear from the application, and object removed from the storage, then there is nothing bad to create a new instance of the object

Javascript not support this feature. I came up with a workaround:

At each object constructing, we increase the number of links by one, and with each destructuring we reduce the number of links by one. and when the number of links is zero, we manually delete the object from the storage.

class Cat {

  storage = {}


  constructor(id) {
    if(storage[id]) {
      var cat = storage[id]
      cat.links++
      return cat
    }

    storage[id] = this
    this.links = 1
  }


  destroy() {
    if(--this.links) {
      delete storage[this._id]
    }
  }

}

usage:

cat1 = new Cat('id')
cat2 = new Cat('id')

cat1 === cat2 // true
cat1.destroy() // storage NOT empty
cat2.destroy() // storage is empty

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