08. Template Method Pattern
HomeDesign PatternC++

08. Template Method Pattern

What is template method in C++

09. Virtual Destructor
07. Prototype Pattern
06. LSP

DesignPattern

Intent

  • Do not duplicate code among child classes

Explain

Usually, child classes provide different features with the similar code. Code 1 shows how multiple child classes are implemented.

// 01_C_AlgorithmAmongClasses.cpp
#include <iostream>
#include <vector>
using namespace std;

class BaseClass
{
public:
    virtual void foo()
    {
        cout << "Mutex lock" << endl;
        cout << "Foo for Base class" << endl;
        cout << "Mutex unlock" << endl;
    }
};

class DerivedClassFirst : public BaseClass
{
public:
    virtual void foo()
    {
        cout << "Mutex lock" << endl;
        cout << "Foo for First derived class" << endl;
        cout << "Mutex unlock" << endl;
    }
};

class DerivedClassSecond : public BaseClass
{
public:
    virtual void foo()
    {
        cout << "Mutex lock" << endl;
        cout << "Foo for Second derived class" << endl;
        cout << "Mutex unlock" << endl;
    }
};

int main()
{
    vector<BaseClass*> v;

    v.push_back(new BaseClass);
    v.push_back(new DerivedClassFirst);
    v.push_back(new DerivedClassSecond);

    for(BaseClass* p : v)
    {
        p->foo();
    }

    return 0;
}
// Compile: clang++ -std=c++14
//          -o 01_C_AlgorithmAmongClasses 01_C_AlgorithmAmongClasses.cpp
C++
Code 1. Algorithm among child classes
Mutex lock
Foo for Base class
Mutex unlock
Mutex lock
Foo for First derived class
Mutex unlock
Mutex lock
Foo for Second derived class
Mutex unlock

The implementation of BaseClass, DerivedClassFirst and DerivedClassSecond are very similar to each other, but only the second output lines are different. The first and third lines are duplicated among the classes. In this case, if we want to change the first or the third line, we should visit each classes. However, Don't Repeat Your code(DRY) is one of refactoring rules. Therefore, we will remove the duplicated code.

To remove the duplicated code, it is necessary to distinguish unchangeable part and changeable part. In Code 1, unchangeable part is the first and third lines. The changeable part in Code 1 is the second line. Each class has its own second line.

After distinction, unchangeable part should be move to a non virtual function of the parent class. A non virtual function is common part of all child classes, so it might be a good entrance.

This is templace method pattern (or Non Virtual Interface(NVI)), and Code 2 shows how to implement it.

// 02_C_TemplateMethod.cpp
#include <iostream>
#include <vector>
using namespace std;

class BaseClass
{
public:
    void foo()
    {
        cout << "Mutex lock" << endl;
        fooImpl();
        cout << "Mutex unlock" << endl;
    }

protected:
    virtual void fooImpl()
    {
        cout << "Foo for Base class" << endl;
    }
};

class DerivedClassFirst : public BaseClass
{
public:
    virtual void fooImpl() override
    {
        cout << "Foo for First derived class" << endl;
    }
};

class DerivedClassSecond : public BaseClass
{
public:
    virtual void fooImpl() override
    {
        cout << "Foo for Second derived class" << endl;
    }
};

int main()
{
    vector<BaseClass*> v;

    v.push_back(new BaseClass);
    v.push_back(new DerivedClassFirst);
    v.push_back(new DerivedClassSecond);

    for(BaseClass* p : v)
    {
        p->foo();
    }

    return 0;
}
// Compile: clang++ -std=c++14
//              -o 02_C_TemplateMethod 02_C_TemplateMethod.cpp
C++
Code 2. Template method
Mutex lock
Foo for Base class
Mutex unlock
Mutex lock
Foo for First derived class
Mutex unlock
Mutex lock
Foo for Second derived class
Mutex unlock

The non virtual function, foo() includes the first line and the third line of Code 1. Also, each class has its virtual function, fooImpl(), and the function includes the second line of Code 1. As a result, the result of Code 1 and Code 2 are the same, but there is no duplicated code.

Normally, algorithm is unchangeable part. The first and third lines are used to prepare for or finish the actual work, the second line. So, they are necessary common step, and part of algorithm. Therefore, they are included in the parent class.

Summary

  • Template method pattern is to implement unchangeable part in parent class and implement changeable part in child class.
  • Algorithm is unchangeable part, so it is implemented in the parent class.
Name

0 weights,1,abstract class,1,active function,3,adam,2,Adapter,1,affine,2,argmax,1,back propagation,3,binary classification,3,blog,2,Bucket list,1,C++,11,Casting,1,cee,1,checkButton,1,cnn,3,col2im,1,columnspan,1,comboBox,1,concrete class,1,convolution,2,cost function,6,data preprocessing,2,data set,1,deep learning,31,Design Pattern,12,DIP,1,django,1,dnn,2,Don't Repeat Your code,1,drop out,2,ensemble,2,epoch,2,favicon,1,fcn,1,frame,1,gradient descent,5,gru,1,he,1,identify function,1,im2col,1,initialization,1,Lab,9,learning rate,2,LifeLog,1,linear regression,6,logistic function,1,logistic regression,3,logit,3,LSP,1,lstm,1,machine learning,31,matplotlib,1,menu,1,message box,1,mnist,3,mse,1,multinomial classification,3,mutli layer neural network,1,Non Virtual Interface,1,normalization,2,Note,21,numpy,4,one-hot encoding,3,OOP Principles,2,Open Close Principle,1,optimization,1,overfitting,1,padding,2,partial derivative,2,pooling,2,Prototype,1,pure virtual function,1,queue runner,1,radioButton,1,RBM,1,regularization,1,relu,2,reshape,1,restricted boltzmann machine,1,rnn,2,scrolledText,1,sigmoid,2,sigmoid function,1,single layer neural network,1,softmax,6,softmax classification,3,softmax cross entropy with logits,1,softmax function,2,softmax regression,3,softmax-with-loss,2,spinBox,1,SRP,1,standardization,1,sticky,1,stride,1,tab,1,Template Method,1,TensorFlow,31,testing data,1,this,2,tkinter,5,tooltip,1,Toplevel,1,training data,1,vanishing gradient,1,Virtual Copy Constructor,1,Virtual Destructor,1,Virtual Function,1,weight decay,1,xavier,2,xor,3,
ltr
item
Universe In Computer: 08. Template Method Pattern
08. Template Method Pattern
What is template method in C++
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s0/
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s72-c/
Universe In Computer
https://kunicom.blogspot.com/2018/03/08-template-method.html
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/2018/03/08-template-method.html
true
2543631451419919204
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago 1 minutes ago 1 hour ago 1 hours ago Yesterday 1 days ago 1 weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy