策略模式和上节提到的 模板模式有很多相似之处
模板模式链接
本文用策略模式实现上节模板模式相同的冒泡排序算法
可以发现
模板模式的 变化都下沉到子类, 通过继承实现
策略模式 变化在于组合的对象, 通过组合实现
简单代码实现
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class BubbleSorterInterface {
public:
[[nodiscard]] virtual bool compare(int index) const = 0;
virtual void swap(int) = 0;
[[nodiscard]] virtual size_t length() const = 0;
};
// 冒泡排序
class BubbleSorter {
private:
BubbleSorterInterface* sorter;
public:
explicit BubbleSorter(BubbleSorterInterface* bsi) : sorter(bsi) {}
void setSorterInterface(BubbleSorterInterface* bsi) {
sorter = bsi;
}
virtual void doSort() {
for (int i = 0; i < sorter->length() - 1; i++) {
for (int j = 0; j < sorter->length() - i - 1; j++) {
if (sorter->compare(j)) {
sorter->swap(j);
}
}
}
}
private:
};
class intBubbleSorterInterface : public BubbleSorterInterface {
private:
vector<int> &_data;
public:
explicit intBubbleSorterInterface(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();
}
};
class stringBubbleSorterInterface : public BubbleSorterInterface {
private:
vector<string> &_data;
public:
explicit stringBubbleSorterInterface(vector<string> &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};
BubbleSorterInterface* bi = new intBubbleSorterInterface(int_data);
BubbleSorter bs(bi);
bs.doSort();
cout << "int sort answer: ";
for (auto v : int_data) {
cout << v << " ";
}
cout << endl;
vector<string> str_data = {"hell world", "I love you", "good bye"};
BubbleSorterInterface* bis = new stringBubbleSorterInterface(str_data);
bs.setSorterInterface(bis);
bs.doSort();
cout << "string sort answer: ";
for (auto &str : str_data) {
cout << "[" << str << "] ";
}
cout << endl;
}