DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

JavaScript Design Patterns - Behavioral - Template

The template pattern allows defining the skeleton of an algorithm in the superclass but lets subclasses override specific algorithm steps without changing its structure.

In this example, We are creating a simple template method to calculate taxes and extending this template to VAT and GST (type of taxes). In this way, we can reuse the same structure in several tax classes.

class Tax {
  calc(value) {
    if (value >= 1000) {
      value = this.overThousand(value);
    }

    return this.complementaryFee(value);
  }

  complementaryFee(value) {
    return value + 10;
  }
}

class VAT extends Tax {
  constructor() {
    super();
  }

  overThousand(value) {
    return value * 1.1;
  }
}

class GST extends Tax {
  constructor() {
    super();
  }

  overThousand(value) {
    return value * 1.2;
  }
}

export { VAT, GST };
Enter fullscreen mode Exit fullscreen mode

A complete example is here šŸ‘‰ https://stackblitz.com/edit/vitejs-vite-ccbqh8?file=template.js

Conclusion

Use this pattern when you want to let clients extend only particular steps of an algorithm but not the whole algorithm or its structure.


I hope you found it helpful. Thanks for reading. šŸ™

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

Image of Timescale

Timescale ā€“ the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
code_passion profile image
CodePassion ā€¢

This was a fantastic read!

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay