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
/* 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 ,...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.