DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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 };
Enter fullscreen mode Exit fullscreen mode

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:

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay