Template method is a behavioral design pattern that defines the framework of an algorithm in a superclass, allowing subclasses to override the specific aspects of the algorithm without modifying the structure. step.
The template method superclass defines fixed processing steps, and the subclass defines a specific implementation of one or several steps.
Example
AbstractClass.h
#ifndef ABSTRACT_METHOD_H_
#define ABSTRACT_METHOD_H_
#include <iostream>
// 抽象类: 银行业务办理流程
class BankTemplateMethod {
public:
void takeNumber() {
std::cout << "排队取号。" << std::endl;
}
virtual void transact() = 0;
void evalute() {
std::cout << "反馈评分。" << std::endl;
}
void process() {
takeNumber();
transact();
evalute();
}
};
#endif // ABSTRACT_METHOD_H_
ConcreteClass.h
#ifndef CONCRETE_METHOD_H_
#define CONCRETE_METHOD_H_
#include "AbstractClass.h"
// 具体类: 存款
class Deposit : public BankTemplateMethod {
public:
void transact() override {
std::cout << "存款..." << std::endl;
}
};
// 具体类: 取款
class Withdraw : public BankTemplateMethod {
public:
void transact() override {
std::cout << "取款..." << std::endl;
}
};
// 具体类: 转账
class Transfer : public BankTemplateMethod {
public:
void transact() override {
std::cout << "转账..." << std::endl;
}
};
#endif // CONCRETE_METHOD_H_
main.cpp
#include "ConcreteClass.h"
int main() {
// 存款
BankTemplateMethod* deposit = new Deposit();
deposit->process();
delete deposit;
// 取款
BankTemplateMethod* withdraw = new Withdraw();
withdraw->process();
delete withdraw;
// 转账
BankTemplateMethod* transfer = new Transfer();
transfer->process();
delete transfer;
}
Compile and run:
$g++ -g main.cpp -o templatemethod -std=c++11
$./templatemethod
排队取号。
存款...
反馈评分。
排队取号。
取款...
反馈评分。
排队取号。
转账...
反馈评分。