Ashish Patel: Notes

Atom feed

Recently added: Xunit, Publisher subscriber pattern, Request reply pattern, Middleware pattern, Command pattern

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:45:03+05:18, updated 2020-08-21T10:16:12+05:18 · History · Edit