模板模式,目的是提供一个代码框架, 而将细节下沉到子类
其和策略模式非常的相似
差别之一是
策略模式:借助组合+委托实现
模板模式:借助继承
模板模式适合在那种流程固化的地方使用,比如说各种框架里面,主类封装好流程, 业务逻辑下沉到子类实现
简单理解版本
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 模板模式
// 父类维持框架, 控制大体流程
// 细节下沉子类, 应对局部细节
// 冒泡排序
class abstractBubbleSorter {
public:
void doSort() {
for (int i = 0; i < length() - 1; i++) {
for (int j = 0; j < length() - i - 1; j++) {
if (compare(j)) {
swap(j);
}
}
}
}
private:
// 细节下沉到子类
[[nodiscard]] virtual bool compare(int index) const = 0;
virtual void swap(int) = 0;
[[nodiscard]] virtual size_t length() const = 0;
};
class intBubbleSorter : public abstractBubbleSorter {
private:
vector<int> &_data;
public:
explicit intBubbleSorter(vector<int> &data) : _data(data) {}
private:
[[nodiscard]] bool compare(int index) const override {
return _data[index] > _data[index + 1];
}
void swap(int index) override {
::swap(_data[index], _data[index + 1]);
}
[[nodiscard]] size_t length() const override {
return _data.size();
}
};
int main(int argc, char **argv) {
// int 冒泡排序
vector<int> int_data = {1, 3, 2, 5, 7, 4};
intBubbleSorter is(int_data);
is.doSort();
cout << "int sort answer: ";
for (auto v : int_data) {
cout << v << " ";
}
cout << endl;
}
输出
优化版本
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 模板模式
// 父类维持框架, 控制大体流程
// 细节下沉子类, 应对局部细节
// 冒泡排序
class abstractBubbleSorter {
public:
void doSort() {
for (int i = 0; i < length() - 1; i++) {
for (int j = 0; j < length() - i - 1; j++) {
if (compare(j)) {
swap(j);
}
}
}
}
private:
// 细节下沉到子类
[[nodiscard]] virtual bool compare(int index) const = 0;
virtual void swap(int) = 0;
[[nodiscard]] virtual size_t length() const = 0;
};
template<typename T>
class TypeBubbleSorter : public abstractBubbleSorter {
private:
vector<T> &_data;
public:
explicit TypeBubbleSorter(vector<T> &data) : _data(data) {}
private:
[[nodiscard]] bool compare(int index) const override {
return _data[index] > _data[index + 1];
}
void swap(int index) override {
::swap(_data[index], _data[index + 1]);
}
[[nodiscard]] size_t length() const override {
return _data.size();
}
};
// 取别名
using intBubbleSorter = TypeBubbleSorter<int>;
using stringBubbleSorter = TypeBubbleSorter<std::string>;
using doubleBubbleSorter = TypeBubbleSorter<double>;
int main(int argc, char **argv) {
// int 冒泡排序
vector<int> int_data = {1, 3, 2, 5, 7, 4};
intBubbleSorter is(int_data);
is.doSort();
cout << "int sort answer: ";
for (auto v : int_data) {
cout << v << " ";
}
cout << endl;
// string 冒泡排序
vector<string> str_data = {"hell world", "I love you", "good bye"};
stringBubbleSorter ss(str_data);
cout << "string sort answer: ";
for (auto &str : str_data) {
cout << "[" << str << "] ";
}
cout << endl;
}