Ashish Patel: Notes

Atom feed

Recently added: Conventional commits, Cli, Shortcuts, Subscriptions, Topic

Singleton Design Pattern

Example

// CashRegister.js

let cash = 0

const CashRegister = {
  credit(amount) {
    cash = cash + amount
    return cash
  },
  debit(amount) {
    if (amount <= cash) {
      cash = cash - amount
      return true
    } else {
      return false
    }
  },
  total() {
    return cash
  },
}

module.exports = CashRegister
// App.js

const cashRegister = require('./CashRegister')
const cashRegister2 = require('./CashRegister')

cashRegister.credit(10)
cashRegister2.credit(20)
cashRegister.debit(5)
console.log(cashRegister.total()) // answer is 25 as both object are using same instance

Created 2019-01-23T11:57:03+05:30, updated 2020-08-21T10:28:12+05:30 · History · Edit