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:

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 (1)

Collapse
 
code_passion profile image
CodePassion โ€ข

This was a fantastic read!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more