Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
State Method Design Patterns in JavaScript
Next article icon

Template Method | JavaScript Design Patterns

Last Updated : 17 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure across different subclasses.

Template-Method-Design-Pattern-in-Java-banner

Important Topics for the Template Method in JavaScript Design Patterns

  • Uses of Template Method in JavaScript
  • Example for Template Method in JavaScript:
  • Advantages of Template Method in JavaScript
  • Disadvantages of Template Method in JavaScript

Use Cases of the Template Method in JavaScript Design Patterns

The Template Method design pattern in JavaScript can be useful in various scenarios where you want to create a common algorithm structure while allowing flexibility for specific implementations. Here are some common uses of the Template Method pattern in JavaScript:

  • UI Frameworks:
    • When building user interface frameworks or libraries, you can use the Template Method pattern to define a common structure for components (e.g., buttons, dialogs) while allowing developers to customize the rendering, event handling, or other behavior of those components in subclasses.
  • Data Processing:
    • In data processing or data transformation tasks, you can define a template method that outlines the overall process (e.g., loading data, transforming it, and saving it) while letting subclasses implement the specific data transformation logic.
  • Game Development:
    • In game development, you can use the Template Method pattern to define common game loops, character behaviors, or level designs while allowing different games or characters to implement their unique features within the established framework.
  • HTTP Request Handling:
    • When dealing with HTTP request handling, you can create a template method for request processing that includes common steps like authentication, request parsing, and response generation, while letting specific routes or endpoints define their custom logic.
  • Algorithmic Processing:
    • For algorithmic tasks, you can use the Template Method pattern to define the overall algorithm structure and let subclasses provide their implementations for specific algorithmic steps.
  • Testing Frameworks:
    • In the development of testing frameworks, you can use the Template Method pattern to define the overall testing process (e.g., setup, execution, teardown) while allowing custom test cases or test suites to specify their unique test logic.
  • Document Generation:
    • When generating documents or reports, you can define a template method that outlines the structure and content of the document, such as headers, footers, and sections, while allowing subclasses to provide the specific content for each section.
  • Middleware and Filters:
    • In web applications, you can use the Template Method pattern to define middleware or filter chains, where each middleware can perform specific tasks before or after the main request handling process, such as authentication, logging, or security checks.
  • State Machines:
    • When implementing state machines, you can use the Template Method pattern to define a common structure for state transitions, error handling, and actions to perform on state changes, with subclasses specifying the details for each state.
  • Code Generators:
    • In code generation tools, you can use the Template Method pattern to define code generation processes, such as parsing input, generating code, and handling dependencies, while allowing customization for different programming languages or target platforms.

Example for Template Method in JavaScript Design Patterns:

We can take the example of a sandwich to demonstrate the Template method in Javascript Design Patterns. Imagine you have a recipe for a sandwich, but some parts of it can vary. The Template Method is like the overall structure of making the sandwich, and the specific ingredients and steps can be customized.

  1. Bread (Fixed Step): You always start with two slices of bread, which is a fixed step in making any sandwich.These steps are fixed and remain unchanged
  2. Custom Filling (Customizable Step): Next, you have the freedom to choose your filling. You can make a ham sandwich, a turkey sandwich, or a vegetarian sandwich. This part is like a customizable step because it varies depending on your choice.These customizable parts can vary based on specific needs.
  3. More Fixed Steps (Fixed Steps): After putting in your filling, you might add some lettuce, tomatoes, and mayonnaise. These are fixed steps that are the same for all sandwiches, no matter the filling.
  4. Top Bread (Fixed Step): Finally, you finish with another slice of bread on top, another fixed step to complete the sandwich.

So, in JavaScript, the Template Method is like a blueprint for making sandwiches. It defines the fixed steps (like using bread at the beginning and end) and leaves some parts (like the filling) open for customization. Different sandwiches (subclasses) can follow the same overall structure while allowing for variations in the filling.

Diagrammatic explanation of the Above Example

Here's a simple diagram to illustrate the key components and interactions:

Template-Method-Design-Pattern-in-JavaScript

Explanation:

  1. AbstractClass: This is the abstract base class that defines the template method (templateMethod) and the individual steps cutBread(), addFilling(),addCondiments(),wrap() . The template method is responsible for orchestrating the algorithm's flow.
  2. ConcreteClass: This is a concrete subclass that extends AbstractClass. It provides specific implementations for some or all of the steps VeggieSandwich,TurkeySandwich while inheriting the structure of the template method from the abstract class.
  3. Instantiate and use ConcreteClass: In your JavaScript code, you create an instance of ConcreteClass and call the templateMethod. The template method follows the predefined algorithm structure and calls the concrete implementations provided by ConcreteClass for the steps. This allows you to reuse the algorithm structure while customizing specific behaviors as needed in derived classes.

Code Implementation of the above Problem:

The Template Method pattern promotes code reuse and separation of concerns by defining a common algorithm structure in the abstract class while allowing flexibility for specific implementations in concrete subclasses.

JavaScript
// Base Sandwich class with the template method
class Sandwich {
  make() {
    this.cutBread();
    this.addFilling();
    this.addCondiments();
    this.wrap();
  }

  cutBread() {
    console.log('Cutting the bread.');
  }

  addCondiments() {
    console.log('Adding condiments (mayonnaise, mustard, etc.).');
  }

  wrap() {
    console.log('Wrapping the sandwich.');
  }

  // Abstract method for adding filling
  addFilling() {
    throw new Error('Subclasses must implement the addFilling method.');
  }
}

// Subclass 1: Veggie Sandwich
class VeggieSandwich extends Sandwich {
  addFilling() {
    console.log('Adding veggies (lettuce, tomato, cucumber, etc.).');
  }
}

// Subclass 2: Turkey Sandwich
class TurkeySandwich extends Sandwich {
  addFilling() {
    console.log('Adding turkey slices.');
  }
}

// Create and make sandwiches
const veggieSandwich = new VeggieSandwich();
const turkeySandwich = new TurkeySandwich();

console.log('Making a Veggie Sandwich:');
veggieSandwich.make();

console.log('\nMaking a Turkey Sandwich:');
turkeySandwich.make();

Output
Making a Veggie Sandwich:
Cutting the bread.
Adding veggies (lettuce, tomato, cucumber, etc.).
Adding condiments (mayonnaise, mustard, etc.).
Wrapping the sandwich.

Making a Turkey Sandwich:
Cutting ...

In this example,

  • Sandwich is the base class that defines the template method make(), which includes fixed steps like cutting the bread, adding condiments, and wrapping the sandwich. The addFilling() method is marked as an abstract method, which means it must be implemented by subclasses.
  • VeggieSandwich and TurkeySandwich are subclasses that extend the Sandwich class. They implement the addFilling() method to specify the filling for each type of sandwich.
  • When you create instances of these sandwich subclasses and call the make() method, the template method ensures that the fixed steps are followed (cutting the bread, adding condiments, wrapping), and the custom filling is added as specified in the subclasses.

Note: This allows you to create a common structure for algorithms while allowing flexibility for specific implementations in derived classes.

Advantages of the Template Method in JavaScript Design Patterns

The Template Method design pattern offers several advantages in software development:

  1. Code Reusability: The primary benefit of the Template Method pattern is code reuse. By defining a common template for an algorithm in an abstract class, you can reuse the same algorithm structure in multiple concrete subclasses. This reduces code duplication and promotes a more maintainable codebase.
  2. Consistency: The pattern enforces a consistent structure for a particular algorithm across different parts of an application or within different subclasses. This consistency can lead to a more predictable and understandable codebase.
  3. Separation of Concerns: The pattern helps separate the overall algorithm structure from the specific implementation details. This separation allows developers to focus on individual steps or components of the algorithm independently, making it easier to maintain and update the code.
  4. Reduced Errors: Since the algorithm's structure is defined in a single place (the abstract class), there is a reduced chance of introducing errors when implementing the same algorithm in different parts of the codebase.
  5. Easy Maintenance: When changes are required in the algorithm's structure or behavior, you only need to make modifications in one place—the abstract class. This simplifies maintenance and ensures that the changes are propagated consistently to all subclasses.
  6. Improved Collaboration: The Template Method pattern can enhance collaboration among team members by providing a clear structure and guidelines for implementing specific parts of an algorithm. It makes it easier for team members to work on different aspects of the code independently.
  7. Enhanced Readability: Code that follows the Template Method pattern tends to be more readable and understandable.
  8. Testing: It facilitates testing because you can test the abstract algorithm and its individual steps independently. This makes it easier to write unit tests for the algorithm's components.

Disadvantages of the Template Method in JavaScript Design Patterns

While the Template Method design pattern offers several advantages, it also has some potential disadvantages and considerations:

  1. Rigidity: The pattern can introduce rigidity into the codebase because the overall algorithm structure is defined in the abstract class. Any significant changes to this structure may require modifications in multiple concrete subclasses, which can be time-consuming and error-prone.
  2. Complexity: In some cases, using the Template Method pattern can lead to increased complexity, especially when dealing with a large number of concrete subclasses or when the algorithm has many variations. Understanding and maintaining the relationships between the abstract class and its subclasses can become challenging.
  3. Limited Flexibility: While the Template Method pattern allows for customization of specific steps, it may not handle scenarios where the algorithm's structure needs to change significantly between subclasses. In such cases, it may be more appropriate to use other design patterns or a more flexible approach.
  4. Inheritance Issues: The pattern relies on class inheritance, which can lead to issues such as the diamond problem (when a class inherits from two classes that have a common ancestor). Careful consideration and management of class hierarchies are necessary to avoid inheritance-related problems.
  5. Tight Coupling: Concrete subclasses are tightly coupled to the abstract class, as they rely on its structure and may override its methods. This can make it difficult to change the abstract class without affecting the concrete subclasses.
  6. Limited Support for Runtime Changes: The Template Method pattern is primarily suited for defining the algorithm structure at compile time. If you need to change the algorithm dynamically at runtime, it may not be the most suitable pattern, and you may consider using other approaches, such as strategy patterns or dependency injection.
  7. Overhead: In some cases, creating a hierarchy of abstract classes and concrete subclasses to implement the Template Method pattern can introduce additional complexity and overhead. This can be especially true for small or simple algorithms where the benefits of the pattern may not outweigh the added complexity.
  8. Maintenance Challenges: While the pattern can simplify maintenance in some cases, it may complicate maintenance in others, especially if the codebase has evolved over time with many concrete subclasses and variations of the template method.
  9. Not Always the Best Fit: The Template Method pattern is not always the best fit for every situation. It's essential to evaluate whether it aligns with the specific requirements and design goals of a given project. In some cases, alternative patterns or approaches may be more suitable.

Next Article
State Method Design Patterns in JavaScript

A

akansha13102003
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023
  • JavaScript Design Patterns

Similar Reads

    JavaScript Design Patterns Tutorial
    Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
    7 min read

    Creational Software Design Patterns in JavaScript

    Builder Method | JavaScript Design Pattern
    The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
    9 min read
    Prototype Method - JavaScript Design Pattern
    A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
    3 min read
    Abstract Factory Pattern | JavaScript Design Patterns
    Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
    6 min read

    Behavioural Software Design Patterns in JavaScript

    Template Method | JavaScript Design Patterns
    Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
    10 min read
    State Method Design Patterns in JavaScript
    State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
    4 min read
    Iterator Method | JavaScript Design Pattern
    Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
    4 min read
    Strategy Method | JavaScript Design Pattern
    Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
    8 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences