Created
April 4, 2018 21:22
-
-
Save Dammmien/524d1c694a3e3d49cf3487145e4c370f to your computer and use it in GitHub Desktop.
JavaScript Strategy design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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