模板方法模式
主要解决父类中不稳定的方法,延迟到子类中去实现的问题。
抽象类代码如下:
#pragma once
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include<iostream>
using namespace std;
class Library {
public:
void Run() {
step1();
if (step2()) {//支持变化,多态调用
step3();
}
for (int i = 0; i < 4;++i) {
step4();//支持变化,多态调用
}
step5();
}
virtual ~Library() {}
protected:
void step1() {
cout << "excute step1" << endl;
}
void step3() {
cout << "excute step3" << endl;
}
void step5() {
cout << "excute step5" << endl;
}
virtual bool step2() = 0;
virtual void step4() = 0;
};
#endif // ! TEMPLATE_H
文件template.h中,step2()和step4()方法都是不稳定的,执行流程Run()由于也是稳定的,所以写在父类中。子类复写不稳定的方法:
#include<iostream>
#include"template.h"
using namespace std;
class Application :public Library {
protected:
bool step2() override {
cout << "excute step2 in derived" << endl;
return true;
}
void step4() override {
cout << "excute step4 in derived" << endl;
}
};
int main()
{
Library* library = new Application();//多态调用
library->Run();//多态调用
delete library;
return 0;
}
子类复写不稳定的方法,然后调用时直接多态调用。
运行结果如下: