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.
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<iostream> //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::cout<<"Non Virtual Base class Start() define skeleton of Algorithm, defere some step to derived class"<<std::endl; SetSpeed(); SetInclination(); Display(); std::cout<<"Base Class Start() End"<<std::endl; } private: virtual void SetSpeed() { std::cout<<"Base Class function"<<std::endl; m_speed += 10;} virtual void SetInclination() { m_inclination += 10; } void Display() {std::cout<<"Base Class Display"<<" Speed:"<<m_speed<<" Inclination:"<<m_inclination<<std::endl; } }; //CustomTreadMill Class, its Derived Class class CustomTreadMill:public TreadMill { virtual void SetSpeed() {std::cout<<"Derived Class function"<<std::endl; m_speed += 20;} virtual void SetInclination() { m_inclination += 20; } }; //Client int main() { std::cout<<"Template Method Design Pattern"<<std::endl; TreadMill tm; tm.Start(); CustomTreadMill ctm; ctm.Start(); return 0; }
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