Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Visitor Method Design Patterns in C++
Next article icon

Template Method Design Pattern | C++ Design Patterns

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs.

When-Does-a-Distributed-System-Need-ZooKeeper-copy-8-(1)

Important Topics for Template Method Design Pattern

  • Example for Template Method Design Pattern in C++
  • Advantages of the State Pattern in C++ Design Patterns
  • Disadvantages of the State Pattern in C++ Design Patterns
  • Conclusion

Example for Template Method Design Pattern in C++

Problem Statement:

We have to design a system for building different types of vehicles.

Key Components of Template Method Design Pattern in C++

These components help define a common algorithm structure while allowing specific steps to be customized by subclasses. Here are the key components of the Template Method Pattern:

  • Template Method: The template method is a method in an abstract base class (or interface) that defines the overall algorithm structure. It consists of a series of steps, some of which are implemented in the base class and others that are left abstract or virtual for concrete subclasses to implement.
  • Abstract Methods (or Hooks): These are abstract or virtual methods declared in the abstract base class (or interface) that represent steps of the algorithm to be implemented by concrete subclasses.
  • Concrete Classes: Concrete classes are derived from the abstract base class and provide concrete implementations for the abstract methods.
  • Template or Base Class: The template or base class is an abstract class (or interface) that declares the template method and may include some default implementations of steps.
  • Client: The client is the code that uses the template method pattern. It creates instances of concrete classes and invokes the template method to execute the algorithm.

Implementation of above Problem in C++:

VehicleTemplate ):

Responsibility: Defines the overall algorithm structure for building a vehicle. It includes a template method ("buildVehicle") that orchestrates the steps of vehicle construction.

Abstract Methods:

  • assembleBody: To be implemented by concrete classes for assembling the body of the vehicle.
  • installEngine: To be implemented by concrete classes for installing the engine.
  • addWheels: To be implemented by concrete classes for adding wheels to the vehicle.
C++
// Step 1: Template Method (Abstract Class) class VehicleTemplate { public:     // Template method defines the algorithm structure     void buildVehicle() {         assembleBody();         installEngine();         addWheels();         std::cout << "Vehicle is ready!\n";     }      // Abstract methods to be implemented by concrete classes     virtual void assembleBody() = 0;     virtual void installEngine() = 0;     virtual void addWheels() = 0; }; 

Car and Motorcycle(Concrete Classes):

Responsibility: Concrete implementations of the abstract class "VehicleTemplate". They provide specific details for building different types of vehicles.

Implementation of Abstract Methods:

  • "Car" implements "assembleBody", "installEngine", and "addWheels" methods for building a car.
  • "Motorcycle" implements similar methods created for building a motorcycle.
C++
class Car : public VehicleTemplate { public:     void assembleBody() override {         std::cout << "Assembling car body.\n";     }      void installEngine() override {         std::cout << "Installing car engine.\n";     }      void addWheels() override {         std::cout << "Adding 4 wheels to the car.\n";     } };  class Motorcycle : public VehicleTemplate { public:     void assembleBody() override {         std::cout << "Assembling motorcycle frame.\n";     }      void installEngine() override {         std::cout << "Installing motorcycle engine.\n";     }      void addWheels() override {         std::cout << "Adding 2 wheels to the motorcycle.\n";     } }; 

Main Function(Client Code): Demonstrates how to use the template method pattern by creating instances of "Car" and "Motorcycle" and invoking their "buildVehicle" method. Output: Shows the result of building a car and a motorcycle, including the specific steps executed in the construction process.

C++
int main() {     std::cout << "Building a Car:\n";     Car car;     car.buildVehicle();      std::cout << "\nBuilding a Motorcycle:\n";     Motorcycle motorcycle;     motorcycle.buildVehicle();      return 0; } 

Below is the complete combined code of the above example:

C++
#include <iostream>  // Step 1: Template Method (Abstract Class) class VehicleTemplate { public:     // Template method defines the algorithm structure     void buildVehicle() {         assembleBody();         installEngine();         addWheels();         std::cout << "Vehicle is ready!\n";     }      // Abstract methods to be implemented by concrete classes     virtual void assembleBody() = 0;     virtual void installEngine() = 0;     virtual void addWheels() = 0; };  // Step 2: Concrete Classes class Car : public VehicleTemplate { public:     void assembleBody() override {         std::cout << "Assembling car body.\n";     }      void installEngine() override {         std::cout << "Installing car engine.\n";     }      void addWheels() override {         std::cout << "Adding 4 wheels to the car.\n";     } };  class Motorcycle : public VehicleTemplate { public:     void assembleBody() override {         std::cout << "Assembling motorcycle frame.\n";     }      void installEngine() override {         std::cout << "Installing motorcycle engine.\n";     }      void addWheels() override {         std::cout << "Adding 2 wheels to the motorcycle.\n";     } };  // Step 3: Client Code int main() {     std::cout << "Building a Car:\n";     Car car;     car.buildVehicle();      std::cout << "\nBuilding a Motorcycle:\n";     Motorcycle motorcycle;     motorcycle.buildVehicle();      return 0; } 

Output:

Building a Car:
Assembling car body.
Installing car engine.
Adding 4 wheels to the car.
Vehicle is ready!
Building a Motorcycle:
Assembling motorcycle frame.
Installing motorcycle engine.
Adding 2 wheels to the motorcycle.
Vehicle is ready!

Diagrammatical Representation of Template Method Design Pattern in C++

Untitled
Diagrammatical Representation of Template Method Pattern in C++
  • VehicleTemplate (Abstract Class): Represents the abstract class "VehicleTemplate". Contains abstract methods ("assembleBody", "installEngine", "addWheels") that need to be implemented by concrete subclasses. Defines the template method "buildVehicle", which manages the algorithm's structure.
  • Car (Concrete Class): Represents the concrete class "Car" that inherits from "VehicleTemplate". Implements specific details for building a car, providing concrete implementations for the abstract methods (("assembleBody", "installEngine", "addWheels").
  • Motorcycle (Concrete Class): Represents the concrete class "Motorcycle" that also inherits from "VehicleTemplate". Implements specific details for building a motorcycle, providing concrete implementations for the abstract methods (("assembleBody", "installEngine", "addWheels").
  • Arrows (Inheritance Relationships): The arrows indicate the inheritance relationships between "VehicleTemplate" and its concrete subclasses ("Car" and "Motorcycle") "Car" and "Motorcycle" inherit the template method and abstract methods from "VehicleTemplate".
  • Method Implementation: The + assembleBody(), + installEngine(), and + addWheels() within Car and Motorcycle indicate that these methods are implemented in these concrete classes.

Advantages of the Template Method Design Pattern in C++

  • Code Reusability: The Template Method pattern promotes the reuse of the common algorithm structure defined in the template method across multiple subclasses. This reduces code duplication.
  • Flexibility: Concrete subclasses have the flexibility to customize specific steps of the algorithm by providing their implementations for abstract methods. This allows for variations in behavior without altering the overall algorithm structure.
  • Consistent Structure: The template method defines a clear and consistent structure for the algorithm, ensuring that certain steps are executed in a specific sequence. This consistency improves code structure and readability.
  • Encapsulation: The pattern encapsulates the details of the algorithm within the abstract class, separating the high-level algorithm from the specific implementations. This encapsulation enhances modularity.
  • Maintenance Ease: Modifications to the common algorithm structure in the template method automatically affects all subclasses. This simplifies maintenance efforts, limiting modifications to the abstract class only.

Disadvantages of the Template Method Design Pattern in C++

  • Inflexibility of Inheritance: The pattern relies on inheritance, and excessive use of inheritance can lead to inflexible designs. Subclasses are bound to the structure defined in the abstract class, and changes to the overall structure may require modifications in multiple places.
  • Limited Runtime Modifications: The template method is defined at compile-time, and changes to the algorithm structure may require modifying the abstract class. This can limit the ability to make runtime changes to the algorithm.
  • Code Duplication in Concrete Classes: While the template method promotes reuse, there might still be cases where concrete subclasses share common code that cannot be abstracted into the template method. This can lead to code duplication in the concrete classes.
  • Potential for Large Hierarchies: As the number of concrete subclasses increases, the template method may become more complex, resulting in large class hierarchies. This can make the system harder to understand and maintain.
  • Difficulty in Understanding the Flow: For developers unfamiliar with the pattern, understanding the flow of control between the template method and abstract methods in different subclasses might be challenging. This can impact the readability of the code.

Conclusion

The Template Method Pattern in C++ is a is a powerful and flexible design pattern for creating robust and adaptable software designs, that facilitates the creation of algorithms with a common structure while allowing specific steps to be customized by subclasses. By understanding its principles and using its key components, developers can build frameworks and systems that can efficiently handle variations in algorithm while maintaining a structured and organized codebase.


Next Article
Visitor Method Design Patterns in C++

R

rudra1807raj
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023

Similar Reads

  • Modern C++ Design Patterns Tutorial
    Design patterns in C++ help developers create maintainable, flexible, and understandable code. They encapsulate the expertise and experience of seasoned software architects and developers, making it easier for newer programmers to follow established best practices. What are C++ Design Patterns?A des
    7 min read
  • Creational Software Design Patterns in C++

    • Factory Method Pattern | C++ Design Patterns
      Factory Method Pattern provides an interface for creating objects but leaves the actual object instantiation to derived classes. This allows for flexibility in object creation and promotes loose coupling between the client code and the concrete products. Table of Content What is the Factory Method D
      8 min read
    • Abstract Factory Pattern | C++ Design Patterns
      Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are
      6 min read
    • Builder Pattern | C++ Design Patterns
      The builder pattern is defined as a creational design pattern that separates the construction of a complex object from its representation, allowing us to create different representations of an object using the same construction process. It's beneficial when an object has many optional properties or
      6 min read
    • Prototype Pattern | C++ Design Patterns
      When designing software, it's crucial to make it efficient, easy to reuse, and simple to maintain. One way to achieve these goals is by using design patterns, and one such pattern is the Prototype Pattern. In this article, we'll explore the Prototype Design Pattern in the context of C++. Important T
      5 min read
    • Singleton Pattern | C++ Design Patterns
      A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have
      11 min read
    • Structural Software Design Patterns in C++

      • Adapter Pattern | C++ Design Patterns
        Adapter Pattern is a structural design pattern used to make two incompatible interfaces work together. It acts as a bridge between two incompatible interfaces, allowing them to collaborate without modifying their source code. This pattern is particularly useful when integrating legacy code or third-
        6 min read
      • Bridge Method | C++ Design Patterns
        Bridge Pattern is basically a structural design pattern in software engineering or in C++ programming that is used to separate an object's abstraction from its implementation. It is part of the Gang of Four (GoF) design patterns and is particularly useful when we need to avoid a permanent binding be
        9 min read
      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