Search⌘ K
AI Features

Challenge: Solution Review

Explore how to apply the command pattern to separate request execution from invocation in JavaScript. Understand the roles of commands, receiver, and invoker by reviewing a BankAccount example with operations like withdraw, deposit, and check amount, improving your grasp of behavioral design patterns.

We'll cover the following...

Solution #

Node.js
class Command {
execute(args) {};
}
//Withdraw command
class WithDrawAmount extends Command {
constructor(bankaccount) {
super();
this.bankaccount = bankaccount;
}
execute(args) {
this.bankaccount.withdrawMoney(args);
}
}
//CheckAmount command
class CheckAmount extends Command {
constructor(bankaccount) {
super();
this.bankaccount = bankaccount
}
execute() {
this.bankaccount.checkAmount()
}
}
//DepositAmount command
class DepositAmount extends Command {
constructor(bankaccount) {
super();
this.bankaccount = bankaccount
}
execute(args) {
this.bankaccount.depositAmount(args)
}
}
//Invoker
class AccountManager {
request(command,args) {
command.execute(args);
}
}
//Reciever:
class BankAccount {
constructor(amount){
this.amount = amount
}
checkAmount() {
console.log(this.amount)
}
withdrawMoney(withdrawamount) {
if(withdrawamount > this.amount){
console.log("Not enough money")
}
else{
this.amount -= withdrawamount
}
}
depositAmount(money){
this.amount += money
}
}
const manager = new AccountManager();
const account = new BankAccount(100)
const check = new CheckAmount(account);
manager.request(check)
const withdraw = new WithDrawAmount(account);
const deposit = new DepositAmount(account);
manager.request(withdraw,10)
manager.request(check)
manager.request(deposit,50)
manager.request(check)

Explanation #

Let’s start by looking at the original code first:

Node.js
class BankAccount {
constructor(amount){
this.amount = amount
}
checkAmount() {
console.log(this.amount)
}
withdrawMoney(withdrawamount) {
if(withdrawamount > this.amount){
console.log("Not enough money")
}
else{
this.amount -= withdrawamount
}
}
depositAmount(money){
this.amount += money
}
}
var account = new BankAccount(100)
account.checkAmount()
account.withdrawMoney(10)
account.checkAmount()
account.depositAmount(50)
account.checkAmount()

In the example, there is a BankAccount class which contains the following functions:

  • checkAmount: returns the amount in the account

  • withdrawMoney: withdraws an amount

  • depositAmount: deposits an amount

An account object will be able to call on these functions directly. With the command pattern, we will change that. This means the object executing the function will be separated from the one requesting. As mentioned in the question, the command ...