WeakMap Pattern Singleton without memory leak

318 views Asked by At
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

1

There are 1 answers

0
Maxmaxmaximus On

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