Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Created April 4, 2018 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dammmien/524d1c694a3e3d49cf3487145e4c370f to your computer and use it in GitHub Desktop.
Save Dammmien/524d1c694a3e3d49cf3487145e4c370f to your computer and use it in GitHub Desktop.
JavaScript Strategy design pattern
class ShoppingCart {
constructor(discount) {
this.discount = new discount();
this.amount = 0;
}
checkout() {
return this.discount.apply(this.amount);
}
setAmount(amount) {
this.amount = amount;
}
}
class discountStrategy {
apply(amount) {
return amount;
}
}
class guestDiscount extends discountStrategy {
apply(amount) {
return amount;
}
}
class regularDiscount extends discountStrategy {
apply(amount) {
return amount * 0.9;
}
}
class premiumDiscount extends discountStrategy {
apply(amount) {
return amount * 0.8;;
}
}
const guest = new ShoppingCart(guestDiscount);
guest.setAmount(10);
console.log(guest.checkout()); // 10
const regular = new ShoppingCart(regularDiscount);
regular.setAmount(10);
console.log(regular.checkout()); // 9
const premium = new ShoppingCart(premiumDiscount);
premium.setAmount(10);
console.log(premium.checkout()); // 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment