"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > JavaScript Design Patterns - Behavioral - Strategy

JavaScript Design Patterns - Behavioral - Strategy

Published on 2024-11-01
Browse:868

JavaScript Design Patterns - Behavioral - Strategy

The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.

In this example, We have a set of discounts that can be applied to a shopping cart. We can pass the function that we will apply to the constructor and, in that way, change the amount discounted.

class ShoppingCart {
  constructor(discount) {
    this.discount = discount;
    this.amount = 0;
  }

  checkout() {
    return this.discount(this.amount);
  }

  setAmount(amount) {
    this.amount = amount;
  }
}

function guest(amount) {
  return amount;
}

function regular(amount) {
  return amount * 0.9;
}

function premium(amount) {
  return amount * 0.8;
}

export { ShoppingCart, guest, regular, premium };

A complete example is here ? https://stackblitz.com/edit/vitejs-vite-tygwh3?file=strategy.js

Conclusion

Use this pattern when you have a lot of similar classes that only differ in how they execute some behavior.


I hope you found it helpful. Thanks for reading. ?

Let's get connected! You can find me on:

  • Medium: https://medium.com/@nhannguyendevjs/
  • Dev: https://dev.to/nhannguyendevjs/
  • Hashnode: https://nhannguyen.hashnode.dev/
  • Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
  • X (formerly Twitter): https://twitter.com/nhannguyendevjs/
  • Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Release Statement This article is reproduced at: https://dev.to/nhannguyendevjs/javascript-design-patterns-behavioral-strategy-152d?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3