简体   繁体   中英

Javascript Flyweight with WeakMap or WeakSet

I want a Flyweight object so I created an Object and stored it's instances in a Map like this:

const FlyweightNumber = (function(){

    "use strict";

    const instances = new Map();

    class FlyweightNumber{

        constructor(number){

            Object.defineProperty(this, 'number', {
                value: number
            });

            if(!instances.get(number)){
                instances.set(number, this);
            }
            else {
                return instances.get(number);
            }

        }

        toString() {
            return this.number;
        }

        valueOf(){
            return this.number;
        }

        toJSON(){
            return this.number;
        }

    }

    return FlyweightNumber;

})();

module.exports = FlyweightNumber;

The problem is that when I'm not using a FlyweightNumber value anymore it is still in memory, stored in this Map.

Since WeakMap and WeakSet are supposed to let garbage colector clear it if it is not used anymore, how could I write a constructor to return the object in the WeakSet or WeakMap or create a new object if it is not stored anymore?

You're looking for a soft reference to implement your number cache. Unfortunately, JS doesn't have these.

And its WeakMap doesn't create weak references either, it's an ephemeron actually. It does not allow you to observe whether an object has been collected.

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