Design Patterns #3

Behavioural Design Patterns is concerned with assignment of responsibilities between the objects. What makes them different from structural patterns is they don't just specify the structure but also outline the patterns for message passing/communication between them

by bhupendra negi

HTML

Behavioural Design Patterns
<ul>
<li>Chain Of Responsibility</li>
<li>Command</li>
<li>Mediator</li>
<li>Observer</li>
</ul>

JavaScript

/*  Behaviour 
It is concerned with assignment of responsibilities between the objects. 
What makes them different from structural patterns is they don't just specify the structure but also outline the patterns for message passing/communication between them
*/

/*
1) Chain of Responsibility 
It helps in building chain of objects, Request enter form one side and pass through each object untill it finds a suitable handler.
Like : if 3 payments methods are attached - ( A - (usd 300) , B-(usd 500) , C-(usd 1000)) , then if cart amount is usd 400 , then first payment A is checked , then it moves to second payment method B as A does not has sufficient balance , so now chain breaks.
*/
console.group('Chain of Responsibility')
class Account {
  setNext(account) {
    this.successor = account;
  }
  canPay(amount) {
    return this.balance >= amount
  }
  pay(amount) {
    if (this.canPay(amount)) {
      this.balance -= amount;
      console.log(`Paying by ${this.name} amount : ${amount} , Balance left : ${this.balance}`)
    } else if (this.successor) {
      console.log(`Not enough Balance in ${this.name} , Proceeding ahead...`);
      this.successor.pay(amount);
    } else {
      console.log('Not enought amount !!!')
    }
  }
}

class Bank extends Account {
  constructor(balance) {
    super();
    this.name = "Bank";
    this.balance = balance;
  }
}

class Paypal extends Account {
  constructor(balance) {
    super();
    this.name = "Paypal";
    this.balance = balance;
  }
}

class CreditCard extends Account {
  constructor(balance) {
    super();
    this.name = "Credit Card";
    this.balance = balance;
  }
}

// using 
const bank = new Bank(100);
const paypal = new Paypal(300);
const creditcard = new CreditCard(800);

bank.setNext(paypal);
paypal.setNext(creditcard);
console.log(bank);
bank.pay(250);
bank.pay(50);
bank.pay(75);
console.groupEnd('Chain of Responsibility');

/*
2) Command pattern is used to decouple client from reciever 
Like: In resturant ,...