How to implement Singleton in Node.js
https://grokonez.com/node-js/how-to-implement-singleton-in-node-js-example
Singleton is object that can have only a single, unique instance, with a single point of access. Node.js module system provides simple way to implement Singleton using module.exports
. Module will be cached when it is accessed using require()
statement. So our module is merely a cached instance although it behaves like a Singleton.
In this tutorial, we're gonna look at ways to implement this kind of Singleton in Node.js:
- Singleton Object
- Singleton Class
Node.js Singleton Object example
We will create a Bank
object, it has 3 methods:
-
deposit()
increasescash
. -
withdraw()
decreasescash
. -
total()
returnscash
.
Bank.js
let cash = 0;
const Bank = {
deposit(amount) {
cash += amount;
return cash;
},
withdraw(amount) {
if (amount <= cash) {
cash -= amount;
return true;
} else {
return false;
}
},
total() {
return cash;
}
}
module.exports = Bank;
Bank
object behaves like a Singleton because we will use module.exports
and require()
statement (not use new
keyword).
app.js
const fund = require('./Bank');
const atm1 = require('./Bank');
const atm2 = require('./Bank');
fund.deposit(10000)
atm1.deposit(20)
atm2.withdraw(120)
console.log(`total-atm1: ${atm1.total()}`)
console.log(`total-atm2: ${atm2.total()}`)
fund.deposit(2000)
console.log(`total-fund: ${fund.total()}`)
As you can see, we create 3 Bank
s (fund
, atm1
, atm2
), every Bank
object can deposit or withdraw money. But all of the action work with only one the cash
insides Bank
.
Here is the result (run with node app.js
command):
total-atm1: 9900
total-atm2: 9900
total-fund after funding 2000: 11900
More at: https://grokonez.com/node-js/how-to-implement-singleton-in-node-js-example
Latest comments (0)