vendredi 14 mai 2021

should I be creating singleton? [closed]

I am using ipfs. Before using it, ipfs.create needs to be called and once it's created, I think, it can be used through the whole app. It's like when you start a node app, you initialize database only 1 time and then include the same instance of db to interact with it instead of running database start in each file..

After ipfs.create, Then I can use ipfs.add() multiple times in my component.

I am thinking of a design choice.

Way 1: Should I create a singleton class ? because every time, I need Ipfs class, I can just import that singleton class and whenever I import this class, it will always be the same in the whole app.

Way 2:

I can just have:

class Ipfs {

    private _ipfs:any;

    async addToIpfs(file:any) {
        if(this._ipfs) {
            this._ipfs = await IPFS.create();
        }

        return await this._ipfs.add(file);
    }
}

export default new Ipfs;

Since ES6 imports are cached, if 2 files import this Ipfs class, they will still get the same instance, which means calling addToIpfs from multiple components will still result in one instance of IPFS.create()..

I really don't know what's the advantage of Way 1 and Way 2.

I'd appreciate the answer..

Aucun commentaire:

Enregistrer un commentaire