Y
Y
Yaroslav Ivanov2020-04-25 23:35:35
Node.js
Yaroslav Ivanov, 2020-04-25 23:35:35

How to apply singleton pattern in node.js?

How to apply singleton pattern in node.js in different files without using global object?

App structure
app/app.js
app/files/Shop.js
app/files/Fruits.js

app.js

let Shop = require("./files/Shop");
let shop = new Shop();


Fruits.js
let Shop = require("./Shop");
let shop = Shop.getInstance(); // цель - получение ссылки на созданный экземпляр в app.js


Since the file is connected again, respectively, all those variables or static properties (Shop.instance) that are created in it to store a link to the instance are recreated.

Solution:

Shop.js
class Shop {
    constructor() {
        this._store = null;
    }

    setStore(value) {
        this._store = value;
    }

    getStore(value) {
        return this._store;
    }
}

module.exports = new Shop();


app.js
let shop = require("./files/Shop");

shop.setStore("apple");


Fruits.js
let shop = require("./Shop");

shop.getStore(); // "apple"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gregory K., 2020-04-26
@space2pacman

You don't show anywhere how you do the export.
By themselves, CommonJS modules already implement Singleton.

// app/app.js
const Shop = require("./files/Shop");
const shop = new Shop();

module.exports = shop;

// app/files/Fruits.js
const shop = require('../app'); // shop, созданный в app.js, будет всегда один и тот же

When including the file require('../app'); again, the same shop will be obtained.
If you want to get shop from the Shop module, then you can create it once there and export it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question