策略模式概述
策略模式是一种行为设计模式,允许在运行时选择算法的行为。它将算法封装在独立的类中,使它们可以相互替换。这种模式使得算法可以独立于使用它的客户端变化。
在C++中,策略模式通常通过抽象基类或接口定义算法族,具体策略类实现这些接口,上下文类持有策略对象的引用并在需要时调用其方法。
策略模式结构
策略模式包含三个主要组件:
- 策略接口:定义所有支持的算法或行为的公共接口
- 具体策略:实现策略接口的具体算法类
- 上下文:持有一个策略对象的引用,通过策略接口与具体策略交互
C++实现示例
下面是一个完整的C++策略模式实现示例,展示了排序算法的策略模式应用:
#include <iostream>
#include <vector>
#include <algorithm>
// 策略接口
class SortStrategy {
public:
virtual void sort(std::vector<int>& data) const = 0;
virtual ~SortStrategy() = default;
};
// 具体策略:冒泡排序
class BubbleSort : public SortStrategy {
public:
void sort(std::vector<int>& data) const override {
std::cout << "Sorting using Bubble Sort\n";
for (size_t i = 0; i < data.size(); ++i) {
for (size_t j = 0; j < data.size() - i - 1; ++j) {
if (data[j] > data[j + 1]) {
std::swap(data[j], data[j + 1]);
}
}
}
}
};
// 具体策略:快速排序
class QuickSort : public SortStrategy {
public:
void sort(std::vector<int>& data) const override {
std::cout << "Sorting using Quick Sort\n";
quickSort(data, 0, data.size() - 1);
}
private:
void quickSort(std::vector<int>& data, int low, int high) const {
if (low < high
### 策略模式概述
策略模式是一种行为设计模式,允许在运行时选择算法的行为。它将算法封装在独立的类中,使它们可以相互替换。这种模式使得算法可以独立于使用它的客户端变化。
在C++中,策略模式通常通过抽象基类或接口定义算法族,具体策略类实现这些接口,上下文类持有策略对象的引用并在需要时调用其方法。
### 策略模式结构
策略模式包含三个主要组件:
1. **策略接口**:定义所有支持的算法或行为的公共接口
2. **具体策略**:实现策略接口的具体算法类
3. **上下文**:持有一个策略对象的引用,通过策略接口与具体策略交互
### C++实现示例
下面是一个完整的C++策略模式实现示例,展示了排序算法的策略模式应用:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// 策略接口
class SortStrategy {
public:
virtual void sort(std::vector<int>& data) const = 0;
virtual ~SortStrategy() = default;
};
// 具体策略:冒泡排序
class BubbleSort : public SortStrategy {
public:
void sort(std::vector<int>& data) const override {
std::cout << "Sorting using Bubble Sort\n";
for (size_t i = 0; i < data.size(); ++i) {
for (size_t j = 0; j < data.size() - i - 1; ++j) {
if (data[j] > data[j + 1]) {
std::swap(data[j], data[j + 1]);
}
}
}
}
};
// 具体策略:快速排序
class QuickSort : public SortStrategy {
public:
void sort(std::vector<int>& data) const override {
std::cout << "Sorting using Quick Sort\n";
quickSort(data, 0, data.size() - 1);
}
private:
void quickSort(std::vector<int>& data, int low, int high) const {
if (low < high
2249

被折叠的 条评论
为什么被折叠?



