Template Design Pattern C++

Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and template method is also one of the solution so we need to find the problem that template pattern has solved and how ?

This design pattern comes under Behavioral Category (It tells that how objects are communicating with each other (objects have been created already)).

C++ Template Method Design Pattern :

Standard Definition:

Template Method Pattern defines the skeleton of an algorithm in an operation, deferring some steps to sub classes. Template Method, lets sub classes redefine certain steps of an algorithm without changing the algorithm’s structure.

Problem/Requirement:

We want to change the behaviour of object, but don’t want to change the number of steps and order of steps in an algorithm.

Solution:

we can refer some functions to derived class and can the behaviour of object and this solution called as “template design pattern“.

When we will use template pattern:

When there is duplicate code and we can make a single code by referring different behaviour in derived class.

Class Diagram:

Class Diagram of real example:

Source Code of real example in C++:

/* * File:templateMethod.cpp * This file is described the template Method Design Pattern with help of example * Template pattern is structutal Pattern * Author: Aplha * Date: 01 Jan 2021 */ //Header File #include //TreadMill Class class TreadMill < protected: int m_speed; int m_inclination; public: TreadMill():m_speed(0), m_inclination(0)<>virtual ~TreadMill()<> //Start is non virtual and TemplateMethod Function void Start() < std::coutprivate: virtual void SetSpeed() < std::coutvirtual void SetInclination() < m_inclination += 10; >void Display() < std::cout>; //CustomTreadMill Class, its Derived Class class CustomTreadMill:public TreadMill < virtual void SetSpeed() < std::coutvirtual void SetInclination() < m_inclination += 20; >>; //Client int main()

Compilation command:

g++ -std=c++11 templateMethod.cpp

Output:

Template Method Design Pattern
Non Virtual Base class Start() define skeleton of Algorithm, defere some step to derived class
Base Class function
Base Class Display Speed:10 Inclination:10
Base Class Start() End
Non Virtual Base class Start() define skeleton of Algorithm, defere some step to derived class
Derived Class function
Base Class Display Speed:20 Inclination:20
Base Class Start() End